如何在 Spring 中声明一个可选的@Bean?

Eld*_*rry 8 spring javabeans

我想@Bean在我的@Configuration文件中提供一个可选的,如:

@Bean
public Type method(Type dependency) {
    // TODO
}
Run Code Online (Sandbox Code Playgroud)

当找不到依赖项时,不应调用该方法。

怎么做?

Meh*_*lik 8

你需要使用ConditionalOnClass If using SpringBootand Conditional in Spring since 4.0 See If using Spring

示例SpringBoot:-

@Bean
@ConditionalOnClass(value=com.mypack.Type.class)
public Type method() {
    ......
    return ...
}
Run Code Online (Sandbox Code Playgroud)

现在method()只有在com.mypack.Type.classin时才会被调用classpath


Joh*_*hna 7

除了接受的答案之外,您还必须在调用任何需要该依赖项的方法之前检查该依赖项是否已初始化。

@Autowired(required = false) 
Type dependency;

public Type methodWhichRequiresTheBean() {
   ...
}

public Type someOtherMethod() { 
     if(dependency != null) { //Check if dependency initialized
         methodWhichRequiresTheBean();
     }
} 
Run Code Online (Sandbox Code Playgroud)