1 package SpringGenericDi; 2 3 import org.springframework.stereotype.Repository; 4 5 6 public class BaseRepository<T> { 7 8 9 }
1 package SpringGenericDi; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Service; 5 6 7 public class BaseService<T> { 8 @Autowired 9 protected BaseRepository<T> repository; 10 11 public void add(){ 12 System.out.println("BaseService add......"); 13 System.out.println(repository); 14 } 15 16 }
package SpringGenericDi; public class User { }
1 package SpringGenericDi; 2 3 import org.springframework.stereotype.Repository; 4 5 @Repository 6 public class UserRepository extends BaseRepository<User> { 7 }
1 package SpringGenericDi; 2 3 import org.springframework.stereotype.Service; 4 5 @Service 6 public class UserService extends BaseService<User> { 7 }
package SpringGenericDi; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("SpringGenericDi/beans-genericDi.xml"); UserService userService = (UserService) ctx.getBean("userService"); userService.add(); } }
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 6 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.2.xsd"> 9 10 <context:component-scan base-package="SpringGenericDi"></context:component-scan> 11 12 </beans>