Java Spring-使用其他自动连接字段初始化字段
我想解决以下问题的最佳方法是什么 我有一个带有一些依赖项的服务和一个我需要的非bean字段Java Spring-使用其他自动连接字段初始化字段,java,spring,dependencies,autowired,Java,Spring,Dependencies,Autowired,我想解决以下问题的最佳方法是什么 我有一个带有一些依赖项的服务和一个我需要的非bean字段 @Service public class ServiceImpl{ @Autowired OtherService otherService; @Autowired DaoImpl dao; Entity entity; } 我需要使用dao.getDefault()方法初始化“entity”字段,这是我的方法 @Service public class ServiceImpl{ @A
@Service
public class ServiceImpl{
@Autowired
OtherService otherService;
@Autowired
DaoImpl dao;
Entity entity;
}
我需要使用dao.getDefault()方法初始化“entity”字段,这是我的方法
@Service
public class ServiceImpl{
@Autowired
OtherService otherService;
DaoImpl dao;
Entity entity;
@Autowired
public ServiceImpl(DaoImpl dao){
this.dao = dao;
entity = dao.getDefault();
}
}
混合使用基于构造函数和基于字段的依赖项注入是一种很好的做法?我不能使用@PostConstruct
,因为我没有访问spring配置文件的权限来启用它。谢谢你的建议 不,将构造函数注入与字段注入相结合不是好的做法。事实上,仅使用现场注入也被视为不良做法。只需谷歌“构造函数vs字段注入”
因此,我建议对otherService
也使用构造函数注入
BTW1,对所有字段使用private
顺便说一句,@PostConstruct
应该是开箱即用的,无需额外配置
BTW3,您正在构造函数中从数据库检索值。这通常被认为是不好的做法。使用Spring初始化bean有几种方法:
- 构造函数的注入
- 通过设定器进行注射
- 注入@Autowired
还可以将配置样式与Java类上的Spring注释相结合,例如:
@Configuration
@AnnotationDrivenConfig // enable the @Autowired annotation
@ImportXml("classpath:mySpringConfigurationFile.xml")
public class MyConfig {
@Autowired
DaoImpl dao;
@Bean
public ServiceImpl myService() {
// Inject the autowired dao from XML source file.
return new ServiceImpl(dao);
}
}
您需要至少设置leat Spring 2.5和Spring后处理器配置:
<beans>
...
<!-- JavaConfig post-processor -->
<bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/>
</beans>
...
感谢您的建议。在最新版本的Spring中,Thre不是classConfigurationPostProcessor
。Spring2.5是一个古老的版本,不应该使用@PostConstruct
通过注释支持启用,而@cold_ice显然正在使用注释支持:我同意你的看法,Spring2.5已经过时了。但是,其他人可能会使用它,可以在spring-javaconfig.jar中找到ConfigurationPostProcessor。如果您使用的是最新版本的Spring,那么可以忽略关于java配置后处理器的最后一段。