我对Spring DI相当陌生。 我们有两个类,PhysicalService和PhysicalDAO。物理服务实例是使用某个服务处理程序动态创建的,因此它不是spring管理bean。物理DAO实例由Spring Beans管理。有什么方法可以在实际服务中注入物理道?Spring依赖注入
回答
服务处理程序是spring bean吗?然后,您可以将DAO注入到服务处理程序中,并且服务处理程序可以在创建它时将其提供给服务。
或者,您可以使用lookup injection将原型服务bean注入到处理程序中,从而有效地在处理程序中提供一个工厂方法,要求spring实例化该服务。
这就是说,我想知道为什么你需要一个服务处理程序?你确定你不能使用spring创建服务吗?
编辑:如果你能摆脱属性文件我把所有的服务到Spring Bean其ID匹配提供给处理程序的ID,注入应用程序上下文到服务处理程序,并做到:
public Object getInstance(String id) {
return applicationContext.getBean(id);
}
要迁移属性文件Spring bean定义,我会使用正则表达式替换。
我tryig重构现有的代码。服务处理程序正在使用工厂模式,并且正在基于某个ID创建服务实例。我们有getInstance(String id)方法,基于id,我们从属性文件获取类名并为其创建实例。 – 2010-09-18 11:14:32
你说ServiceHandler使用工厂模式打包PhysicalService。
首先,您必须将PhysicalDAO注入工厂,您可以在春季环境中定义它或使用自动布线注记。
//spring-context.xml
<bean id="physicalDAO" class="package.dao.PhysicalDAO">
//inject reference needed by dao class
</bean>
<bean id="physicalServiceFactory" class="package.service.PhysicalServiceFactory">
<property name="physicalDAO" ref="physicalDAO " ></property>
</bean>
,并在你的工厂类,你可以按如下编写代码:
PhysicalServiceFactory {
private PhysicalDAO physicalDAO;
public void setPhysicalDAO(PhysicalDAO _physicalDAO) {
physicalDAO = _physicalDAO;
}
public PhysicalService create(String id) {
PhysicalService ps = PhysicalService(id);
ps.setPhysicalDAO(physicalDAO);
return ps;
}
}
只要你的应用程序是春天的具体应用,下面简单的步骤,可能有助于在注释的方式注入PhysicalDAO到PhysicalService。
//Add this spring annotation to add your DAO class to Spring container
@Component("physicalDAO")
public class PhysicalDAO {
}
//Add Service class with PhysicalDAO object reference to use.
public class PhysicalService {
@Autowired
PhysicalDAO physicalDAO;
}
定义下面的条目给你弹簧配置文件。
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.cognizant.aop.annotation"></context:component-scan>
- 1. Spring依赖注入失败
- 2. Spring传递依赖注入
- 3. Spring依赖注入安全
- 4. Spring Boot + DynamoDBTypeConverter依赖注入
- 5. Guice到Spring依赖注入
- 6. Spring 3依赖注入
- 7. 使用Spring注释注入依赖
- 8. spring 3注解依赖注入
- 9. Spring中的依赖注入失败
- 10. 使用Grails Spring DSL的依赖注入
- 11. Spring依赖注入对象池
- 12. 注入的Spring依赖成JPA EntityListener
- 13. 原因使用Spring依赖注入
- 14. GWT或Spring中的依赖注入
- 15. 如何依赖注入struts2 action with spring?
- 16. 日志Spring bean创建/依赖注入
- 17. 依赖注入Spring框架 - 工作
- 18. Spring MVC中的依赖注入
- 19. Spring依赖注入范围混淆
- 20. 泽西与Spring 4依赖注入
- 21. 在Glassfish中禁用Spring依赖注入
- 22. 使用依赖注入的好处Spring
- 23. Spring依赖注入停止工作
- 24. Spring Java对象依赖注入
- 25. Spring 3.1依赖注入失败
- 26. 向Spring bean注入依赖关系
- 27. Spring 3.0依赖注入的最小JARs
- 28. Spring依赖注入,使用@Named或@Resource?
- 29. Spring依赖注入@Autowired without setter
- 30. Spring - 向ServletContextListener注入依赖项
'使用某些服务处理程序动态创建'它是什么样的处理程序? 或者您创建PhysicalServiceFactory类来创建PhysicalService实例? – 2010-09-18 11:51:41