Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用
示例:
1.Repository 的父类 BaseRegistory
public class BaseRepository<T> { }2.Service的父类 BaseService
BaseService中配置一个泛型的BaseRepository。
public class BaseService<T> { //不在 BaseRepository,BaseService 上加注解,可以被子类继承 @Autowired protected BaseRepository<T> repository; public void add(){ System.out.println("add..."); System.out.println(repository); } }3.Repository实现类 UserRepository
加@Repository注解,配置到Spring容器中
package com.spring.generic.di; import org.springframework.stereotype.Repository; @Repository public class UserRepository extends BaseRepository<User>{ }4.Repository实现类RoleRepository
加@Repository注解,配置到Spring容器中
package com.spring.generic.di; import org.springframework.stereotype.Repository; @Repository public class RoleRepository extends BaseRepository<Role>{ }5.BaseService实现类 UserService
加@Service注解,配置到Spring容器中
package com.spring.generic.di; import org.springframework.stereotype.Service; @Service public class UserService extends BaseService<User>{ }配置文件 略,使用context:component-scan全部扫描进Spring容器即可
6.测试类
public class Main { public static void main(String[] args) { ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml"); UserService userService = (UserService) ctx.getBean("userService"); userService.add(); } }
测试结果:add方法打印出
add...
com.spring.generic.di.RoleRepository@37a98fa9
Spring会根据泛型,将泛型为User的Repository配置给了UserService