I understand that Spring Boot has lots of @Conditional
annotations like, @ConditionalOnBean
, @ConditionalOnClass
, @ConditionalOnProperty
, ConditionalOnWebApplication
. But I do not know how this work?
For Example:
@Configuration @ConditionalOnClass(MyBean.class) public class MyConfiguration{ // omitted }
What I understood is, MyConfiguration
will be loaded only if MyBean
is available in my classpath. But how would it compile and run if MyBean
class is not in my class path as the compiler reaches to @ConditionalOnClass(MyBean.class)
line, wont it throw compiler error? As soon as I add such code in my eclipse, I am getting compile time error. Sorry if this is too basic question but I do not know what I am missing to understand.
Advertisement
Answer
Spring Boot is being compiled with lots of optional dependencies; so when Spring Boot is compiled, the MyBean.class
is on the classpath.
Now your application may not have that MyBean.class
in its classpath, but it doesn’t fail at runtime. This is because the infrastructure that processes @ConditionalOnClass
annotations will actually read the bytecode of the configuration and will only load them if that MyBean.class
is present. See @ConditionalOnClass
javadoc.
Now auto-configuration is a broad subject, and you can learn more about this in this talk.