【问题标题】:Spring - Initialize field using other autowired fieldSpring - 使用其他自动装配字段初始化字段
【发布时间】:2015-12-09 12:39:17
【问题描述】:

我想解决以下问题的最佳方法是什么

我有一个具有一些依赖项的服务和一个我需要的非 bean 字段

@Service
public class ServiceImpl{
 @Autowired
 OtherService otherService;

 @Autowired
 DaoImpl dao;

 Entity entity;
}

我需要使用dao.getDefault() 方法初始化“实体”字段,这是我的方法

@Service
public class ServiceImpl{
 @Autowired
 OtherService otherService;

 DaoImpl dao;

 Entity entity;

 @Autowired
 public ServiceImpl(DaoImpl dao){
  this.dao = dao;
  entity = dao.getDefault();
 }
}

混合基于构造函数和基于字段的依赖注入是一种好习惯吗?我无法使用@PostConstruct,因为我无权访问 spring 配置文件来启用它。感谢所有建议。

【问题讨论】:

    标签: java spring dependencies autowired


    【解决方案1】:

    不,将构造函数注入与字段注入结合起来并不是一个好习惯。事实上,仅使用场注入也被认为是不好的做法。只需谷歌“构造函数与字段注入”。

    所以我建议也对otherService 使用构造函数注入。

    顺便说一句,所有字段都使用private

    BTW2,@PostConstruct 无需额外配置即可开箱即用

    顺便说一句,您正在构造函数中从数据库中检索值。这通常被认为是不好的做法。

    【讨论】:

      【解决方案2】:

      你有几种使用 Spring 初始化 bean 的方法:

      • 构造函数注入。
      • setter 注入。
      • 使用@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);
      }
      

      }

      您至少需要 Spring 2.5 并且必须设置 Spring 后处理器配置:

      <beans>
          ...
          <!-- JavaConfig post-processor -->
          <bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/>
      </beans>
      

      【讨论】:

      • 感谢您的建议
      • Tehre 在 Spring 的最新版本中不是 ConfigurationPostProcessor 类。 Spring 2.5 是旧版本,不应该使用。 @PostConstruct 启用了注释支持,@cold_ice 显然正在使用:docs.spring.io/spring/docs/current/spring-framework-reference/…
      • 我同意你的观点 Spring 2.5 已经过时了。但是其他人可能会使用它,并且 ConfigurationPostProcessor 可以在 spring-javaconfig.jar 中找到。如果你使用的是最新版本的 Spring,你可以忽略最后一段关于 java config post processor。
      猜你喜欢
      • 2015-07-28
      • 2016-02-14
      • 2010-12-27
      • 2014-09-07
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多