I believe this should be simple, but I can't figure it out.
I have a configuration class like this:
@Configuration
@AutoConfigureAfter(MailSenderAutoConfiguration.class)
public class MyMailConfiguration {
@Bean
@ConditionalOnBean(JavaMailSender.class)
public MyMailer myMailer(JavaMailSender javaMailSender) {
return new MyMailer(javaMailSender);
}
}
But MyMailer doesn't get created. If I remove the ConditionalOnBean, JavaMailSender gets injected and MyMailer gets created, but I want the condition there so when I don't have the mail configured, it doesn't crash.
The only option left is to use ConditionalOnProperty and watch for the same properties as the MailSenderAutoConfiguration do, but that stinks.
problem is that @AutoConfigureAfter is not working as you expected. See @AutoConfigureAfter not working as desired
When MyMailConfiguration is processed, there's no garantee that all the beans from MailSenderAutoConfiguration have been created. So ConditionalOnBean is not working (bean doesn't yet exist). When there's no ConditionalOnBean anno, Spring understands the bean creation order graph correctly.
I've written a sample for your problem:
@Configuration
public class RootConfig {
@PostConstruct
public void post(){
System.out.println("RootConfig processed");
}
@Bean
public RootMailer rootMailer(){
System.out.println("Root bean created");
return new RootMailer();
}
}
@Configuration
@AutoConfigureAfter(RootConfig.class)
public class MyConfig {
@PostConstruct
public void post(){
System.out.println("MyConfig processed");
}
@Bean
// @ConditionalOnBean(RootMailer.class)
public MyMailer myMailer(RootMailer javaMailSender) {
System.out.println("MyMail bean created");
return new MyMailer(javaMailSender);
}
}
where RootConfig == MailSenderAutoConfiguration, RootMailer == JavaMailSender
Generation output:
MyConfig processed
RootConfig processed
Root bean created
MyMail bean created
If you uncomment @ConditionalOnBean the order will remain the same, but the bean will not exist at the anno processing moment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With