Spring can parse @Configuration
classes using ClassReader
s
Assuming that we have the following scenario
We have an autoconfiguration class with multiple @Bean
definitions
One of the @Bean
has all conditions passed while second @Bean
have @ConditionalOnClass
& the class is not present in the class path
@Configuration
class CustomConfiguration {
@Bean
@ConditionalOnClass(String.class)
String knownClass() {
return "Hello";
}
@Bean
@ConditionalOnClass(MissingClass.class)
MissingClass secondBean() {
return new MissingClass();
}
}
In this scenario, I have couple of questions
ApplicationContext
?@Bean
method be hit during debug*AutoConfiguration
class get loaded into JVM as this class will refers to other classes (from second @Bean) which cant be resolved at class load time@Bean
method and invoke the method?Thanks
Generally speaking you should avoid using @ConditionalOnClass
on a @Bean
method for this exact reason. This situation is covered in the reference documentation where using a separate @Configuration
class to isolate the @ConditionalOnClass
condition is recommended.
To answer your specific questions:
@Bean
method should be hit during debugging@Bean
method, the class should load successfully. If the unresolvable class is used in the signature of a @Bean
method (typically the return type), the class will fail to load.As noted in the documentation linked to above, rather than worrying about the scenarios described in 3 and what will and will not work, using a separate, probably nested @Configuration
class with a class-level condition is the recommended approach. For your specific example, that would look like this:
@Configuration
class CustomConfiguration {
@Bean
@ConditionalOnClass(String.class)
String knownClass() {
return "Hello";
}
@Configuration
@ConditionalOnClass(MissingClass.class)
static class DoubtfulBeanConfiguration {
@Bean
MissingClass missingClass() {
return new MissingClass();
}
}
}