为什么在Spring的@Configuration中使用@Autowired时有时会失败?

时间:2019-05-15 02:12:29

标签: java spring spring-boot

我在一个节俭服务器上使用Spring Boot,并且我有两个带有两个bean生成方法的@Configuration类,其代码如下:

@Configuration
public class EagleBeanCreator {

    @Bean(destroyMethod = "destroy")
    public EagleRestClient build() {
        EagleRestClient client = new EagleRestClient();
        // some set values code
        return client;
    }
}

还有一个:

@Configuration
public class EagleServiceBuilder {

    @Autowired
    private EagleRestClient eagleProxy;

    @Bean
    public EagleService eagleService() {
        EagleService service = new EagleService();
        System.out.println(eagleProxy);
        service.setEagleProxy(eagleProxy);
        return service;
    }
}

但是当我运行spring-boot:run时,它为“ System.out.println(eagleProxy);”打印出null。 为什么?

=============================================== ========

我知道setter注入或构造函数注入会起作用。

5 个答案:

答案 0 :(得分:2)

因为加载EagleBeanCreatorEagleServiceBuilder的顺序不确定。您可以使用@Order@ConditionalOnClass来确保EagleBeanCreator首先进行初始化。

答案 1 :(得分:1)

您可能想尝试一下。

<div id="clickInsideIt" class="click-inside collapse p-4">
    <mat-form-field>
        <input [(ngModel)]="modal" matInput [matDatepicker]="picker">
        <mat-datepicker-toggle matSuffix [for]="picker" ></mat-datepicker-toggle>
        <mat-datepicker #picker disabled="false" ></mat-datepicker>
    </mat-form-field>
</div>

$(document).click((e) => {
        if (!$(e.target).is("#clickInsideIt")) {
       }
       else{
       }
});

我的猜测是,您当前实现的方式并不表示@Configuration public class EagleServiceBuilder { @Bean public EagleService eagleService(EagleRestClient eagleProxy) { EagleService service = new EagleService(); System.out.println(eagleProxy); service.setEagleProxy(eagleProxy); return service; } } EagleService之间的依赖关系。因此,当前的实现导致两个Bean之间的随机初始化顺序。修改后的版本告诉Spring:“嘿,我的EagleService取决于EagleRestClient。请在EagleRestClient之前初始化EagleRestClient

答案 2 :(得分:0)

因为@Configuration bean在bean生命周期的同一阶段被初始化。我记不清楚他们了,但是类似:

Configurations -> Components -> Services

在Bean处于同一阶段的情况下,如果它们相互依赖,则应通过一些@Conditional@Order声明装载顺序

答案 3 :(得分:0)

在EagleService的定义上添加@DependsOn(“ eagleRestClient”)注释。

@DependsOn("eagleRestClient")
@Bean
 public EagleService eagleService() {
       EagleService service = new 
       EagleService();
       System.out.println(eagleProxy);
       service.setEagleProxy(eagleProxy);
        return service;
  }

然后,Spring将首先创建rest客户,然后是eagle服务。

答案 4 :(得分:-3)

首先,您需要通过ApplicationContextAware试试

ApplicationContext.getBean(EagleRestClient.class)