Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How SpringBoot @ConditionalOnClass work?

Tags:

spring-boot

For example, HttpEncodingAutoConfiguration is annotated with @ConditionalOnClass(CharacterEncodingFilter.class).

What I know about @ConditionalOnClass is to promise the CharacterEncodingFilter in classpath, but if the class not in classpath how could it get through at compile or class loading time.

Thanks a lot.

like image 797
F.Roger Avatar asked Jul 13 '26 03:07

F.Roger


1 Answers

The javadoc on ConditionalOnClass.value gives the answer:

The classes that must be present. Since this annotation is parsed by loading class bytecode, it is safe to specify classes here that may ultimately not be on the classpath, only if this annotation is directly on the affected component and not if this annotation is used as a composed, meta-annotation. In order to use this annotation as a meta-annotation, only use the name attribute.

Also at compile time you do have to have such classes on the classpath to use the value attribute of ConditionalOnClass.

Spring-boot uses optional dependencies to achieve this. In maven this looks like this:

<dependency>
  <groupId>com.atomikos</groupId>
  <artifactId>transactions-jdbc</artifactId>
  <version>4.0.4</version>
  <scope>compile</scope>
  <optional>true</optional>
</dependency>

In gradle you usually use compileOnly to achieve this.

like image 162
Mathias Dpunkt Avatar answered Jul 18 '26 11:07

Mathias Dpunkt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!