Spring框架入门之Spring4.0新特性——泛型注入

Spring框架入门之Spring4.0新特性——泛型注入

1、为了更加快捷的开发,为了更少的配置,特别是针对 Web 环境的开发,从 Spring 4.0 以后,Spring 引入了 泛型依赖注入。spring

2、泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之间的依赖关系来肯定,父类的泛型必须为同一类型。框架

  通俗一点来讲:两个子类之间的依赖关系不须要在子类中去声明,而是在父类中进行了声明,而依赖的纽带就是 泛型类型,必须是相同的父类泛型类型才具备依赖关系。测试

3、代码说明以下:spa

  1.首先创建repository和service的两个基类以下:code

 1 package me.spring.beans.generic.di;  2  3 public class BaseRepository<T> {  4  5 }  6  7 package me.spring.beans.generic.di;  8  9 import org.springframework.beans.factory.annotation.Autowired; 10 11 public class BaseService<T> { 12 13 /** 14  * 泛型注入,子类经过User类型依赖 15  * 控制台打印:UserRepository 即BaseRepository的子类 16  * add.. 17  * me.spring.beans.generic.di.UserRepository@6fb0d3ed 18 */ 19  @Autowired 20 protected BaseRepository<T> baseRepository; 21 public void add() { 22 System.out.println("add.."); 23  System.out.println(baseRepository); 24  } 25 }

  2.两个基类的实现类以下:(经过User实体依赖)xml

 1 package me.spring.beans.generic.di;  2  3 import org.springframework.stereotype.Repository;  4  5 @Repository  6 public class UserRepository extends BaseRepository<User>{  7  8 }  9 10 11 package me.spring.beans.generic.di; 12 13 import org.springframework.stereotype.Service; 14 15 @Service 16 public class UserService extends BaseService<User>{ 17 18 }

  3.User实体blog

1 package me.spring.beans.generic.di; 2 3 public class User { 4 5 }

  4.main测试类:开发

 1 package me.spring.beans.generic.di;  2  3 import org.springframework.context.ApplicationContext;  4 import org.springframework.context.support.ClassPathXmlApplicationContext;  5  6 public class Main {  7  8 public static void main(String[] args) {  9 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic-di.xml"); 10 UserService userService = (UserService) ctx.getBean("userService"); 11  userService.add(); 12  } 13 }

  5.运行代码,控制台打印以下:get

  add..
  me.spring.beans.generic.di.UserRepository@6fb0d3ed
  如上控制台打印:UserRepository 即BaseRepository的子类而不是BaseRepository,这是经过泛型及User实体依赖的结果,相信你们应该已经多多少少有点理解了吧
相关文章
相关标签/搜索