Spring 泛型依赖注入

Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用


示例:
1.Repository  的父类 BaseRegistory
public class BaseRepository<T> {

}
2.Service的父类 BaseService
BaseService中配置一个泛型的BaseRepository。
public class BaseService<T> {
	//不在  BaseRepository,BaseService 上加注解,可以被子类继承
	@Autowired
	protected BaseRepository<T> repository;
	
	public void add(){
		System.out.println("add...");
		System.out.println(repository);
	}
}
3.Repository实现类  UserRepository
加@Repository注解,配置到Spring容器中
package com.spring.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{

}
4.Repository实现类RoleRepository
加@Repository注解,配置到Spring容器中
package com.spring.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class RoleRepository extends BaseRepository<Role>{

}
5.BaseService实现类 UserService
加@Service注解,配置到Spring容器中
package com.spring.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{
	
}
配置文件  略,使用context:component-scan全部扫描进Spring容器即可

6.测试类
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();
	}
}

测试结果:add方法打印出
add...
com.spring.generic.di.RoleRepository@37a98fa9

Spring会根据泛型,将泛型为User的Repository配置给了UserService




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值