泛型依赖注入
- BaseService<T> 类中有一个BaseRepository<T>的成员变量,并且利用@Autowired实现了自动装配。
- UserService 和 UserRepository分别是 BaseService<T> 和 BaseRepository<T>的具体类型的子类。
- 当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