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實體依賴的結果,相信你們應該已經多多少少有點理解了吧
相關文章
相關標籤/搜索