泛型依赖注入
BaseRepository.java
package com.spring.beans.generic.di; public class BaseRepository <T>{ }
BaseService.java
package com.spring.beans.generic.di; import org.springframework.beans.factory.annotation.Autowired; public class BaseService <T>{ @Autowired protected BaseRepository<T>baseRepository; public void add() { System.out.println("add..."); System.out.println(baseRepository); } }
UserRepository.java
package com.spring.beans.generic.di; import org.springframework.stereotype.Repository; @Repository public class UserRepository extends BaseRepository<User>{ }
UserService.java
package com.spring.beans.generic.di; import org.springframework.stereotype.Service; @Service public class UserService extends BaseService<User>{ }
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <context:component-scan base-package="com.spring.beans.generic.di" ></context:component-scan> </beans>
Main.java
public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans-generic-di.xml"); UserService userService = (UserService) applicationContext.getBean("userService"); userService.add(); }
输出
2014-9-22 20:20:17 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@8b819f: startup date [Mon Sep 22 20:20:17 CST 2014]; root of context hierarchy
2014-9-22 20:20:17 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-generic-di.xml]
add...
com.spring.beans.generic.di.UserRepository@c01e99