当使用spring批注@Bean声明某些实例时,将注入(inject)参数,并且这些参数是必需的,如果找不到实例,则会抛出NoSuchBeanException。

如何使其可选?像@Autowired(required = false)这样的东西

例如

@Configuration
class SomeConfiguration {

  @Bean
  public SomeComponent someComponent(Depend1 depend1,
                                     Depend2 depend2) {
    SomeComponent someComponent = new SomeComponent();
    someComponent.setDepend1(depend1);
    if (depend2 != null) {
      someComponent.setDepend2(depend2);
    }
    return someComponent;
  }
}

最佳答案

只需使用Optional:

@Bean
public SomeComponent someComponent(Depend1 depend1, Optional<Depend2> depend2) {
   ...
}

09-11 20:30