Spring IOC容器

九、泛型依赖注入

1.简介

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

2.实现

[1]组件基类

BaseRepository

public class BaseRepository<T> {

public void save() {

System.out.println("Saved by BaseRepository");

}

 

}

BaseService

public class BaseService<T> {

@Autowired

private BaseRepository<T> repository;

public void add() {

repository.save();

}

 

}

[2]组件实体类

UserRepository

@Repository

public class UserRepository extends BaseRepository<User>{

public void save() {

System.out.println("Saved by UserRepository");

}

 

}

UserService

@Service

public class UserService extends BaseService<User>{

 

}

[3]模型实体类

User

public class User {

 

}

[4]测试

ApplicationContext ioc = new ClassPathXmlApplicationContext("di.xml");

 

UserService us = (UserService) ioc.getBean("userService");

 

us.add();

执行结果

Saved by UserRepository