[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>
<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
|
public class User { }
|
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
|
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);
bookService.save();
userService.save(); }
}
|