Spring进入4.0之后有了一个新的特性——泛型依赖注入。
为什么需要泛型依赖注入呢?(本文出自:http://my.oschina.net/happyBKs/blog/482508)
在实际开发中,往往我们可以将一些结构职能相似的类抽象出一定的泛型超类。这样相应结构中的类之间的依赖关系我们可以通过泛型超类来建立,而其他的子类只要继承了它们,就能够建立相应的依赖关系:
Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用,我们用一个例子来看看:
两个泛型超类定义如下,它们之间是依赖关系:依赖关系需要用自动装配@Autowired注解
package com.happyBKs.generic.di;
public class BasicRepository<T> {
public void save()
{
System.out.println("BasicRepository<T> save...");
}
}
package com.happyBKs.generic.di;
import org.springframework.beans.factory.annotation.Autowired;
public class BasicService<T> {
@Autowired
protected BasicRepository<T> basicRepository;
public void add()
{
System.out.println("BasicService<T> add...");
System.out.println(basicRepository);
basicRepository.save();
}
}
我们在定义一个具体类:
package com.happyBKs.generic.di;
public class UserBean {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
String name;
int age;
public UserBean(String name, int age) {
super();
this.name = name;
this.age = age;
}
public UserBean() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "UserBean [name=" + name + ", age=" + age + "]";
}
}
我们用UserBean建立刚才两个泛型超类的子类:别忘了注解,配置为bean
package com.happyBKs.generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BasicRepository<UserBean> {
}
package com.happyBKs.generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BasicService<UserBean> {
}
IOC容器配置文件:src\main\resources\beans-generic-di.xml
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="com.happyBKs.generic.di"></context:component-scan>
</beans>
测试程序:
package com.happBKs.spring.iocaop;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.happyBKs.generic.di.UserService;
public class TestGenericDi {
@Test
public void test1()
{
ApplicationContext ac=new ClassPathXmlApplicationContext("beans-generic-di.xml");
UserService us=(UserService)ac.getBean("userService");
us.add();
//System.out.println(pc);
}
}
运行结果:
BasicService<T> add...
com.happyBKs.generic.di.UserRepository@4aeacb4a
BasicRepository<T> save...
看到了吧,打印出的System.out.println(basicRepository);的是com.happyBKs.generic.di.UserRepository@4aeacb4a
这对于需要建立大量的Repository和Service时十分有用,我不再需要为每一对Repository和Service配置依赖关系,即不需要在每一个Service内加入属性@Autowired注解。