泛型依賴注入

  1. BaseService<T> 類中有一個BaseRepository<T>的成員變量,而且利用@Autowired實現了自動裝配。
  2. UserService 和 UserRepository分別是 BaseService<T> 和 BaseRepository<T>的具體類型的子類。
  3. 當UserService 和 UserRepository分別用@Service 和 @Repository裝配之後,Spring 可讓這兩個子類之間自動實現關聯。具體實現參考代碼:

 

 

  • BaseRepository基類
package spring.beans.generic.di;

public class BaseRepository<T> {

}

 

  • BaseService 基類,在這個基類中利用 @Autowired 實現了對 BaseRepository 屬性的自動裝配
package spring.beans.generic.di;

import org.springframework.beans.factory.annotation.Autowired;

public class BaseService<T> {
    @Autowired
    protected BaseRepository<T> repository; 
    
    public void add(){
    	System.out.println("add...");
    	System.out.println(repository);  	
    }
}

 

  • 泛型類:User
package spring.beans.generic.di;

public class User {
}

 

  • 繼承類: UserRepository 用 @Repository 來裝配
package spring.beans.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User> {

}

 

  • 繼承類:UserService 用 @Service 來裝配
package spring.beans.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User> {

}

 

  • 測試函數:
package spring.beans.generic.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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();	
	}
}

 

  • 測試輸出:從測試輸出咱們能夠看出 ,自動實現了子類之間的相互關聯。
一月 28, 2016 9:36:52 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1f17ae12: startup date [Thu Jan 28 09:36:52 CST 2016]; root of context hierarchy
一月 28, 2016 9:36:52 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans-generic-di.xml]
add...
spring.beans.generic.di.UserRepository@6dde5c8c
相關文章
相關標籤/搜索