Spring4.0新特性--泛型依赖注入
1)Spring4.0可以为子类注入子类的泛型类型,成员变量的引用
下面UML图来说名关系
BaseService<T>:有RoleService和UserService两的子类
BaseRepepositry<T>:有UserRepository和RoleRepositry两个子类
由于BaseService<T>和BaseRepepositry<T>有关系所以,得出下面的子类也存在这样的关系
2)用代码来说话
1.---User.java
1 package com.baba.miao.test.generic.di; 2 3 public class User { 4 5 }
2.---UserRepository.java
1 package com.baba.miao.test.generic.di; 2 3 import org.springframework.stereotype.Repository; 4 5 @Repository //交给IOC容器来管理 6 public class UserRepository extends BaseRepository<User>{ 7 8 }
3.---UserService.java
1 package com.baba.miao.test.generic.di; 2 3 import org.springframework.stereotype.Repository; 4 5 @Repository //交给IOC容器来管理 6 public class UserService extends BaseService<User>{ 7 8 }
4.---BaseService.java
1 package com.baba.miao.test.generic.di; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 5 public class BaseService <T>{ 6 7 //关键所在 8 @Autowired 9 protected BaseRepository<T> repository; 10 11 public void add(){ 12 System.out.println("adding...."); 13 14 System.out.println(repository); 15 } 16 } 17
5.---BaseRepository.java
1 package com.baba.miao.test.generic.di; 2 3 public class BaseRepository <T>{ 4 5 }
6.Test---Main.java (测试)
1 package com.baba.miao.test.generic.di; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Main { 7 8 public static void main(String[] args) { 9 ApplicationContext applicationContext = new ClassPathXmlApplicationContext( 10 "beans-generic.xml"); 11 12 UserService userService = (UserService) applicationContext 13 .getBean("userService"); 14 15 userService.add(); 16 17 } 18 }
7.配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 7 8 <context:component-scan base-package="com.baba.miao.test.generic.di"></context:component-scan> 9 </beans>
好了通过上面的代码就可以说明问题了
本人是一个Java爱好者,欢迎交流
----By 小苗