How does spring-boot @ConditionalOnClass work?

How exactly does the @ConditionalOnClass annotation @ConditionalOnClass ?

My goal is to load a specific bean only if a jar providing this class is included in the classpath.

I thought that I could annotate @Bean with @ConditionalOnClass(MyService.class) and declare the dependency in maven as optional:

 <dependency> <groupId>de.my</groupId> <artifactId>my-framework<artifactId> <optional>true</optional> </dependency> @Bean @ConditionalOnClass(MyService.class) public MyConditionalBean statistics() { return new MyConditionalBean(); } 

Now anyone with a my-framework as a dependency should automatically connect this bean. But anyone who has no addiction should skip it.

But when I run the application, I get the following error:

 Caused by: java.lang.ClassNotFoundException: de.MyService.class at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702) ~[catalina.jar:7.0.50] at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547) ~[catalina.jar:7.0.50] 

So I'm probably doing something wrong. How then can I create a bean conditional for jar dependencies and classes contained in classpath?

From spring documents:

Classes that must be present. Since this annotation is analyzed when loading the bytecode of a class, it is safe to specify classes that may ultimately not be in the classpath.

But the error says something else ...

+18
java spring spring-boot
source share
1 answer

Good catch!

You can use the @Bean method on @Bean , but in this case you must specify your class as a literal String:

 @Bean @ConditionalOnClass(name ="de.MyService") public MyConditionalBean statistics() { return new MyConditionalBean(); } 

I don’t remember the why, but this is from the existing Spring Boot source code.

+17
source share

All Articles