How to define optional parameters (dependencies) in the @Bean method in Spring?

JonasGao :

When use spring annotation @Bean to declare some instances, the arguments be injection, and these are required, if can't find instance, will throw NoSuchBeanException.

How to make it optional? Something like @Autowired(required = false)

For example

@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;
  }
}
Sergi Almar :

Just use Optional:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433534&siteId=1