Search code examples
springjavabeans

How to declare an optional @Bean in Spring?


I want to provide an optional @Bean in my @Configuration file like:

@Bean
public Type method(Type dependency) {
    // TODO
}

when dependency can't be found, the method should not be called.

How to do that?


Solution

  • 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.