14

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?

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
Elderry
  • 1,902
  • 5
  • 31
  • 45
  • 1
    Please see https://stackoverflow.com/questions/29844271/conditional-spring-bean-creation You can use `@Conditional` – questionaire Jan 11 '18 at 08:36

2 Answers2

18

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();
     }
} 
t0r0X
  • 4,212
  • 1
  • 38
  • 34
Johna
  • 1,836
  • 2
  • 18
  • 29
17

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.

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85