一、泛型依赖注入
1、版本一
BaseDao
public abstract class BaseDao<T> {
public abstract void save();
}
StudentDao
@Repository
public class StudentDao extends BaseDao<Student>{
@Override
public void save() {
System.out.println("StudentDao。。。保存学生");
}
}
UserDao
@Repository
public class UserDao extends BaseDao<User>{
@Override
public void save() {
System.out.println("UserDao。。。保存用户");
}
}
StudentService
@Service
public class UserService {
@Autowired
UserDao userDao;
public void save() {
userDao.save();
}
}
UserService
@Service
public class StudentService {
@Autowired
StudentDao studentDao;
public void save() {
studentDao.save();
}
}
测试
@Test
public void test1() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc.xml");
UserService userService = ioc.getBean(UserService.class);
StudentService studentService = ioc.getBean(StudentService.class);
userService.save();
studentService.save();
}
分别调用了自己类中的 dao 层的方法。
2、版本二
可以发现在 service 里面都调用了各自的 dao 层里面的save() 方法,那么就可以抽象出来一个 BaseService。
BaseService:
public class BaseService<T> {
@Autowired
BaseDao<T> baseDao;
public void save(){
System.out.println("自动注入的dao:"+ baseDao );
baseDao.save();
}
}
UserService:
@Service
public class UserService extends BaseService<User>{
}
StudentService:
@Service
public class StudentService extends BaseService<Student>{
}
测试运行:
UserService 和 StudentService 都继承了 BaseService,里面也都有了 baseDao 和 save() 方法,而且 Spring 还可以正确的给各自对应的 dao 赋值。
二、泛型依赖注入原理
带泛型的父类类型:
System.out.println(userService.getClass()); //class com.njf.spring.service.UserService
System.out.println(userService.getClass().getSuperclass()); //class com.njf.spring.service.BaseService
System.out.println(userService.getClass().getGenericSuperclass()); //com.njf.spring.service.BaseService<com.njf.spring.bean.User>