泛型依赖注入

  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

  

 

转载于:https://www.cnblogs.com/shi-yi-ge/p/5165185.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值