How to declare an optional @Bean in Spring?
In addition to the accepted answer, you have to check if the dependency is initialized before calling any method which requires that dependency.
@Autowired(required = false)
Type dependency;
public Type methodWhichRequiresTheBean() {
...
}
public Type someOtherMethod() {
if(dependency != null) { //Check if dependency initialized
methodWhichRequiresTheBean();
}
}
You need to use ConditionalOnClass If using SpringBoot
and Conditional in Spring since 4.0
See If using Spring
Example of SpringBoot
:-
@Bean
@ConditionalOnClass(value=com.mypack.Type.class)
public Type method() {
......
return ...
}
Now the method()
will be called only when com.mypack.Type.class
is in classpath
.