泛型依赖注入
BaseRepository.javapackage com.spring.beans.generic.di;
public class BaseRepository {
}
BaseService.javapackage com.spring.beans.generic.di;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseService {
@Autowired
protected BaseRepositorybaseRepository;
public void add() {
System.out.println("add...");
System.out.println(baseRepository);
}
}
UserRepository.javapackage com.spring.beans.generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository{
}
UserService.javapackage com.spring.beans.generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService{
}
beans-generic-di.xml<?xml version="1.0" encoding="UTF-8"?>
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">
Main.javapublic 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