Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 607
Elderry Avatar asked Jan 11 '18 06:01

Elderry


1 Answers

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.

like image 180
Mehraj Malik Avatar answered Oct 10 '22 09:10

Mehraj Malik