Skip to content
Advertisement

@ConditionalOnClass for `javax.validation.ConstraintViolationException` not working

I have a Spring Boot library that adds autoconfiguration. I am already using @ConditionalOnClass successfully to only activate parts of the library if Spring Security is on the classpath for example.

Currently, my library requires spring-boot-starter-validation as a dependency, and I would like to make this optional. I added @ConditionalOnClass like this:

JavaScript

But when running in an application, I get this error:

JavaScript

Advertisement

Answer

I think you have to put @ConditionalOnClass on the class level. Otherwise Spring Boot still has to load the configuration class to analyze it and this will fail if not all dependencies are on the classpath. If you put @ConditionalOnClass on the configuration class instead, Spring Boot can read this information without actually loading the class and skip class loading if the class declared in @ConditionalOnClass is not on the classpath.

In this case you could even reference the real class in @ConditionalOnClass instead of the class name as string. Just make sure that your dependency is optional so that it’s not included as transitive dependency of your library.

By the way, this was the short answer. The long version can be found here: https://youtu.be/N39hpGAT43s 😉 I really like this presentation. Learned a lot from it.

Advertisement