15Spring泛型依赖注入
Spring 4.x中可以为子类注入子类对应的泛型类型的成员变量的引用
BaseService<T>:有RoleService和UserService两的子类
BaseRepepositry<T>:有UserRepository和RoleRepositry两个子类
由于 BaseService<T>和 BaseRepepositry<T> 有关系所以,得出下面的子类也存在这样的关系
package generic.di; public class BaseRepository<T> { } ———————————————————————————————————————————————————————————————————————————————————————————————————————————————— 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("add"); System.out.println(repository); } }
package generic.di; import org.springframework.stereotype.Repository; @Repository public class RoleRepository extends BaseRepository<Organization> { }
——————————————————————————————————————————————————————————————————————————————————————————————————————————————
package generic.di; import org.springframework.stereotype.Service; @Service public class RoleService extends BaseService<Organization> { }
—————————————————————————————————————————————————————————————————————————————————————————————————————————————— package generic.di; public class Organization { }
package generic.di; public class User { } —————————————————————————————————————————————————————————————————————————————————————————————————————————————— package generic.di; import org.springframework.stereotype.Repository; @Repository public class UserRepository extends BaseRepository<User> { } —————————————————————————————————————————————————————————————————————————————————————————————————————————————— package generic.di; import org.springframework.stereotype.Service; @Service public class UserService extends BaseService<User> { }
<?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.xsd"> <context:component-scan base-package="generic.di"> </context:component-scan> </beans>
package 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("generic/di/15-1.xml"); UserService userService = (UserService) ctx.getBean("userService"); RoleService roleService = (RoleService) ctx.getBean("roleService"); userService.add(); roleService.add(); } }