Java 如何在Spring的@Bean方法中定义可选参数(依赖项)?
当使用spring annotationJava 如何在Spring的@Bean方法中定义可选参数(依赖项)?,java,spring,spring-boot,Java,Spring,Spring Boot,当使用spring annotation@Bean声明一些实例时,参数是注入的,这些是必需的,如果找不到实例,将抛出NoSuchBeanException 如何使它成为可选的?类似于@Autowired(required=false) 比如说 @Configuration class SomeConfiguration { @Bean public SomeComponent someComponent(Depend1 depend1,
@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;
}
}
只需使用
可选:
@Bean
public SomeComponent someComponent(Depend1 depend1, Optional<Depend2> depend2) {
...
}
@Bean
公共SomeComponent SomeComponent(Depend1 Depend1,可选depend2){
...
}
或者您可以这样定义多个配置文件
@Configuration
@Profile("dev")
class DevConfiguration {
@Bean
public SomeComponent someComponent(Depend1 depend1) {
SomeComponent someComponent = new SomeComponent();
someComponent.setDepend1(depend1);
return someComponent;
}
}
及
现在使用命令行参数-Dspring.profiles.active=“dev”
或-Dspring.profiles.active=“prod”
启动应用程序时,它将为您选择正确的bean。如果多个配置文件(例如test和dev)需要相同的实现,您只需将@Profile(“dev”)
替换为@Profile({“dev”,“test”})
您可以对参数使用@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;
}
}
当使用可选
作为参数时,Intellij IDEA将显示建议的警告。如果没有更好的方法,我会使用它。那么intellij应该得到改进,因为这是最好的方法:它清楚地说明了设计:一个强制依赖项和一个可选项,而不使用十亿美元的错误(即null),因为@Profile
可以用于方法,所以你可以有一个配置类。
@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;
}
}