My project references the A jar package, and the A jar package references the B jar package, but the A jar package does not pass the B jar package dependency to my project. There is such a code in the A jar package:
@Configuration
public class Configure {
@Bean
public ClassA configureA(){
return new ClassA();
}
@Bean
@ConditionalOnClass(name="org.example.ClassB")
public ClassB configureB(){
return new ClassB();
}
}
In my project, ClassA exists and ClassB does not exist. I expect configureB not to be called when there is no ClassB, but a ClassNotFound exception will be reported after the Configure class is loaded. If @ConditionalOnClass appears on the class, Configure will not be loaded , because AMS is used to verify the bytecode before loading the class. If the conditional class does not appear, the class will not be loaded. My idea is whether it is possible to use AMS technology to dynamically delete this method when the condition is not met.
Comment From: quaff
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnClass.html
Note: Extra care must be taken when using @ConditionalOnClass on @Bean methods where typically the return type is the target of the condition. Before the condition on the method applies, the JVM will have loaded the class and potentially processed method references which will fail if the class is not present. To handle this scenario, a separate
@Configurationclass should be used to isolate the condition.
Comment From: philwebb
Thanks @quaff, that's the problem here I think. Try:
@Configuration
public class Configure {
@Bean
public ClassA configureA(){
return new ClassA();
}
@Configuration
@ConditionalOnClass(name="org.example.ClassB")
public class ConfigureB {
@Bean
public ClassB configureB(){
return new ClassB();
}
}
}