spring学习笔记十二 泛型注入

泛型依赖注入的优点:

泛型依赖注入就是允许我们在使用spring进行依赖注入的同时,利用泛型的优点对代码进行精简,将可重复使用的代码全部放到一个类之中,方便以后的维护和修改。同时在不增加代码的情况下增加代码的复用性。

BaseRepository.java

package generic.di;

public class BaseRepository<T> {

	public void add(){
		System.out.println("repository add..");
	}
}

BaseService.java

package generic.di;

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

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

package generic.di;

public class User {

}
UserService.java

package generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{

}

UserRepository.java

package generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{

}
generic-di.java

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="generic.di"></context:component-scan>

</beans>

Main.java

package generic.di;

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

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ApplicationContext ctx=new ClassPathXmlApplicationContext("generic-di.xml");
		UserService userService=(UserService) ctx.getBean("userService");
	    userService.add();
	}

}

运行结果:



  • 在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的add方法
  • 在他们的子类中,继承了这种关系,因此我们在测试方法中调用userService.add(); 也是可以成功地调用UserReponsitory中的add方法
  • 根据泛型T自动注入相应的Reponsitory


在网上发现了一篇很详细介绍依赖注入的文章:http://blog.csdn.net/pengxianzhe1/article/details/53522985
















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不染心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值