美文网首页
Spring 泛型依赖注入

Spring 泛型依赖注入

作者: 桑鱼nicoo | 来源:发表于2020-01-26 21:03 被阅读0次

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

    @Service
    public class UserService extends BaseService<User> {}
    
    public class Main {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = (UserService) ctx.getBean("userService");
            System.out.println(userService);
            userService.add();
        }
    }
    
    public class BaseService<T> {
        @Autowired
        protected BaseRepository<T> repository;
    
        public void add(){
            System.out.println("add...");
            System.out.println(repository);
        }
    }
    
    public class BaseRepository<T> { }
    
    @Repository
    public class UserRepository extends BaseRepository<User> {
        @Override
        public String toString() {
            System.out.println("UserRepository");
            return super.toString();
        }
    }
    
    public class User { }
    

    相关文章

      网友评论

          本文标题:Spring 泛型依赖注入

          本文链接:https://www.haomeiwen.com/subject/eonrthtx.html