首页 > 代码库 > Spring之泛型依赖注入

Spring之泛型依赖注入

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

技术分享

项目结构:

技术分享

 

BaseRepository.java

public class BaseRepository<T> {

}

BaseService.java

public class BaseService<T>{
    
        @Autowired
        protected BaseRepository<T> repository;

        public void add(){
            System.out.println("add...");
            System.out.println(repository);
        }
}

User.java

public class User {

}

UserRepository.java

@Repository
public class UserRepository extends BaseRepository<User>{

}

UserService.java

@Service
public class UserService extends BaseService<User>{
    
}

Test.java

public class Test {
    public static void main(String[] args) {
        
        ApplicationContext context=new ClassPathXmlApplicationContext("bean-gi.xml");
        
        UserService service=(UserService) context.getBean("userService");
        
        service.add();

    }
}

 

Spring之泛型依赖注入