[toc]

Spring之泛型依赖注入

Spring 4.x中可以为子类注入子类对应的泛型类型的成员变量的引用。

1. 引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<dependencies>

<!--测试所用的包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

<!--spring框架所用包,有四个-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>


</dependencies>

2. 添加配置文件

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">

<context:component-scan base-package="cn.justweb.calculator"/>

</beans>

3. 实体类

User

1
2
3
4
5
6
7
/**
* @Date 2020/5/25 23:41
* @Version 10.21
* @Author DuanChaojie
*/
public class User {
}

Book

1
2
public class Book {
}

4. Dao

BaseDao

1
2
3
public abstract class BaseDao<T> {
public abstract void save();
}

UserDao

1
2
3
4
5
6
7
@Repository
public class UserDao extends BaseDao<User> {
@Override
public void save() {
System.out.println("我是UserDao中的save方法。");
}
}

BookDao

1
2
3
4
5
6
7
@Repository
public class BookDao extends BaseDao<Book> {
@Override
public void save() {
System.out.println("我是BookDao中的save方法。");
}
}

5. Service

BaseService

1
2
3
4
5
6
7
8
9
10
11
public class BaseService<T> {

@Autowired
private BaseDao<T> baseDao;

@Test
public void save(){
System.out.println("自动注入的dao:"+baseDao);
baseDao.save();
}
}

UserService

1
2
3
@Service
public class UserService extends BaseService<User> {
}

BookService

1
2
3
@Service
public class BookService extends BaseService<Book> {
}

6. 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @Date 2020/5/25 23:57
* @Version 10.21
* @Author DuanChaojie
*/
public class IOCTest {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void test(){
BookService bookService = ioc.getBean(BookService.class);
UserService userService = ioc.getBean(UserService.class);

//自动注入的dao:cn.justweb.calculator.bean.dao.BookDao@3f56875e
//我是BookDao中的save方法。
bookService.save();

//自动注入的dao:cn.justweb.calculator.bean.dao.UserDao@2b4bac49
//我是UserDao中的save方法。
userService.save();
}


}