Spring新特性_泛型依赖注入
泛型依赖注入
package com.tanlei.spring.generic; 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); } }
package com.tanlei.spring.generic; import org.springframework.stereotype.Service; @Service public class UserService extends BaseService<User>{ }
package com.tanlei.spring.generic; public class BaseRepository<T> { }
package com.tanlei.spring.generic; import org.springframework.stereotype.Repository; @Repository public class UserReopsitory extends BaseRepository<User>{ }
package com.tanlei.spring.generic; public class 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-4.0.xsd"> <context:component-scan base-package="com.tanlei.spring.generic"></context:component-scan> </beans>
package com.tanlei.spring.generic; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("bean.generic.xml"); UserService userService=(UserService) context.getBean("userService"); userService.add(); } }