如何在Spring中的@Bean方法中定义可选参数(依赖项)?

时间:2017-10-12 08:33:27

标签: java spring spring-boot

当使用spring注释@Bean声明一些实例时,参数是注入的,这些是必需的,如果找不到实例,将抛出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;
  }
}

3 个答案:

答案 0 :(得分:10)

只需使用Optional

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

答案 1 :(得分:4)

您可以在参数上使用@Autowired(required = false)

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

答案 2 :(得分:1)

或者你可以像这样定义多个配置文件

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

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

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

当您现在使用命令行参数-Dspring.profiles.active="dev"-Dspring.profiles.active="prod"启动应用程序时,它将为您选择正确的bean。如果多个配置文件(例如test和dev)需要相同的实现,您只需将@Profile("dev")替换为@Profile({"dev","test"})