如何在 Spring 中声明一个可选的@Bean?
How to declare an optional @Bean in Spring?
我想在我的 @Configuration
文件中提供一个可选的 @Bean
,例如:
@Bean
public Type method(Type dependency) {
// TODO
}
当找不到依赖项时,不应调用该方法。
怎么做?
您需要使用ConditionalOnClass If using SpringBoot
and Conditional in Spring since 4.0
SpringBoot
示例:-
@Bean
@ConditionalOnClass(value=com.mypack.Type.class)
public Type method() {
......
return ...
}
现在只有当 com.mypack.Type.class
在 classpath
时才会调用 method()
。
除了已接受的答案外,您还必须在调用任何需要该依赖项的方法之前检查该依赖项是否已初始化。
@Autowired(required = false)
Type dependency;
public Type methodWhichRequiresTheBean() {
...
}
public Type someOtherMethod() {
if(dependency != null) { //Check if dependency initialized
methodWhichRequiresTheBean();
}
}
我想在我的 @Configuration
文件中提供一个可选的 @Bean
,例如:
@Bean
public Type method(Type dependency) {
// TODO
}
当找不到依赖项时,不应调用该方法。
怎么做?
您需要使用ConditionalOnClass If using SpringBoot
and Conditional in Spring since 4.0
SpringBoot
示例:-
@Bean
@ConditionalOnClass(value=com.mypack.Type.class)
public Type method() {
......
return ...
}
现在只有当 com.mypack.Type.class
在 classpath
时才会调用 method()
。
除了已接受的答案外,您还必须在调用任何需要该依赖项的方法之前检查该依赖项是否已初始化。
@Autowired(required = false)
Type dependency;
public Type methodWhichRequiresTheBean() {
...
}
public Type someOtherMethod() {
if(dependency != null) { //Check if dependency initialized
methodWhichRequiresTheBean();
}
}