码迷,mamicode.com
首页 > 其他好文 > 详细

泛型依赖注入

时间:2016-01-28 10:46:52      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

  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

  

 

泛型依赖注入

标签:

原文地址:http://www.cnblogs.com/shi-yi-ge/p/5165185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!