springioc之泛型依赖注入_htkzs的博客-爱代码爱编程
首先讲解一下原始的注入方式
public abstract class BaseDao<T> { public abstract void save(); } @Repository public class BookDao extends BaseDao<Book>{ @Override public void save() { System.out.println("保存图书信息 BookDao被调用"); } } @Repository public class StudentDao extends BaseDao<Student>{ @Override public void save() { System.out.println("保存用户信息 StudentDao被调用"); } } @Service public class BookService { @Autowired private BookDao bookdao; public void saveBook(){ bookdao.save(); } } @Service public class StudentService { @Autowired private StudentDao studentDao; public void saveStudent(){ studentDao.save(); } } @ContextConfiguration(locations = "classpath:application02.xml") @RunWith(SpringJUnit4ClassRunner.class) public class SpringJunit4Test { @Autowired private BookService bookService; @Autowired private StudentService studentService; @Test public void save(){ bookService.saveBook(); studentService.saveStudent(); } } 通过测试发现要调用那个具体的持久层Dao都需要,注入具体的Dao 而下来的操作就是通过泛型动态决定要注入那个Dao进行操作。 注意:下面没出现的Dao层代码和上面的代码保持一致。
@Service public class BookService extends BaseService<Book>{ } @Service public class StudentService extends BaseService<Student>{ } public class BaseService<T> { @Autowired private BaseDao<T> baseDao; public void save(){ baseDao.save(); } } 通过泛型决定注入具体调用的那个Dao @ContextConfiguration(locations = "classpath:application02.xml") @RunWith(SpringJUnit4ClassRunner.class) public class SpringJunit4Test { @Autowired private BaseService<Student> baseService; @Test public void save(){ baseService.save(); System.out.println(baseService.getClass().getSuperclass()); //得到带泛型的类的类型名称 System.out.println(baseService.getClass().getGenericSuperclass()); } }
由此可见,当我们传入一个具体的泛型Student后,调用底层的save()就会在BaseService中自动注入StudentDao 进而调用StudentDao的save()方法
Spring在做依赖注入的时候,泛型也是一个考虑的因素。