Spring 5 处理空 Bean 的方式发生了变化? [英] Change in how Spring 5 handles null Beans?

查看:16
本文介绍了Spring 5 处理空 Bean 的方式发生了变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下应用程序:

So, I have the following application:

@SpringBootApplication
public class AutonullApplication {

  public static void main(String[] args) {
    SpringApplication.run(AutonullApplication.class, args);
  }

  @Bean
  First first() {
    return null;
  }

  public class First {
  }

  @Service
  public class Second {

    private final First first;

    public Second(First first) {
      this.first = first;
    }

    @PostConstruct
    public void print() {
      System.out.println("First = " + first);
    }
  }

}

尝试将 First 类型的 bean 注入到 Second 类型的服务中.但是 bean 的值为 null.此代码在 Spring Boot 1.5.10(以及 Spring 4)中运行良好,但在 Spring Boot 2.0(和 Spring 5)中失败:

which tries to inject a bean of type First into a service of type Second. But the bean has a value of null. This code works fine in Spring Boot 1.5.10 (and so Spring 4), but fails in Spring Boot 2.0 (and Spring 5):

说明:

构造函数中的参数1eu.plumbr.autonull.AutonullApplication$Second 需要一个 bean 类型'eu.plumbr.autonull.AutonullApplication$First' 不能找到了.

Parameter 1 of constructor in eu.plumbr.autonull.AutonullApplication$Second required a bean of type 'eu.plumbr.autonull.AutonullApplication$First' that could not be found.

有没有人知道官方文档中提到过这种变化?

Is anybody aware of any mention of such change in the official documentation?

推荐答案

是的,这是 Spring Framework 5 中的一个重大更改.可以说,这样的设置很奇怪,我们想稍微收紧这些规则.

Yes, this is a breaking change in Spring Framework 5. Arguably, such setup is weird and we wanted to tighten those rules a little bit.

如果您请求注入 First 并且您提供了 null,那么认为未提供 bean 更为一致.然后,您可以查询First 是否存在的上下文.@spencergibb 已经解释了如何使用 Optional,或者您可以使用 ObjectProvider 作为注入点:

If you request to inject First and you provide null, then it's more consistent to consider that bean isn't provided. You can then query the context for the presence of First. @spencergibb already explained how you can use Optional, or you can use ObjectProvider<First> as an injection point:

@Service
public class Second {

    private final First first;

    public Second(ObjectProvider<First> first) {
        this.first = first.getIfAvailable(); // return null
    }

}

这篇关于Spring 5 处理空 Bean 的方式发生了变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆