简体   繁体   中英

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

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;
  }
}

Just use Optional :

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

You can use @Autowired(required = false) on a parameter:

@Configuration
class SomeConfiguration {

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

Or you could define multiple profiles like so

@Configuration
@Profile("dev")
class DevConfiguration {

  @Bean
  public SomeComponent someComponent(Depend1 depend1) {
    SomeComponent someComponent = new SomeComponent();
    someComponent.setDepend1(depend1);
    return someComponent;
  }
}

and

@Configuration
@Profile("prod")
class ProdConfiguration {

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

when you now start your application with the command line argument -Dspring.profiles.active="dev" or -Dspring.profiles.active="prod" it'll select the correct bean for you. In case multiple profiles,test and dev for example, require the same implementation you can simply replace @Profile("dev") with @Profile({"dev","test"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM