泛型依赖注入的优点:
泛型依赖注入就是允许我们在使用spring进行依赖注入的同时,利用泛型的优点对代码进行精简,将可重复使用的代码全部放到一个类之中,方便以后的维护和修改。同时在不增加代码的情况下增加代码的复用性。
BaseRepository.java
package generic.di;
public class BaseRepository<T> {
public void add(){
System.out.println("repository add..");
}
}
BaseService.java
package generic.di;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseService<T> {
@Autowired
protected BaseRepository<T> repository;
public void add(){
System.out.println("BaseService add..");
repository.add();
}
}
User.java
package generic.di;
public class User {
}
UserService.java
package generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
UserRepository.java
package generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository<User>{
}
generic-di.java
<?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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="generic.di"></context:component-scan>
</beans>
Main.java
package generic.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx=new ClassPathXmlApplicationContext("generic-di.xml");
UserService userService=(UserService) ctx.getBean("userService");
userService.add();
}
}
运行结果:
- 在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的add方法
- 在他们的子类中,继承了这种关系,因此我们在测试方法中调用
userService.add();
也是可以成功地调用UserReponsitory中的add方法 - 根据泛型T自动注入相应的Reponsitory
在网上发现了一篇很详细介绍依赖注入的文章:http://blog.csdn.net/pengxianzhe1/article/details/53522985