关于spring的泛型依赖注入主要是继承等方面的知识
具体实现的简单的代码如下:
package bao1; public class BaseRepository <T>{ }
package bao1; 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 bao1; import org.springframework.stereotype.Service; @Service public class UserSrevice extends BaseService<User> { }
package bao1; public class User { }
package bao1; import org.springframework.stereotype.Repository; //交个ioc容器管理 @Repository public class UserRepository extends BaseRepository<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.3.xsd"> <context:component-scan base-package="bao1"></context:component-scan> </beans>
package bao1; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Spring { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ct=new ClassPathXmlApplicationContext("bean-06.xml"); UserSrevice userSrevice= (UserSrevice) ct.getBean("userSrevice"); userSrevice.add(); } }