当使用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;
}
}
答案 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"})