本文介绍了Spring boot - 仅当 bean JavaMailSender 存在时自动配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这应该很简单,但我无法弄清楚.

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);
    }
}

但是 MyMailer 没有被创建.如果我删除 ConditionalOnBean,JavaMailSender 会被注入并创建 MyMailer,但我想要条件,所以当我没有配置邮件时,它不会崩溃.

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.

剩下的唯一选择是使用 ConditionalOnProperty 并观察与 MailSenderAutoConfiguration 相同的属性,但这很糟糕.

The only option left is to use ConditionalOnProperty and watch for the same properties as the MailSenderAutoConfiguration do, but that stinks.

推荐答案

问题是 @AutoConfigureAfter 没有按预期工作.见@AutoConfigureAfter 无法正常工作

problem is that @AutoConfigureAfter is not working as you expected.See@AutoConfigureAfter not working as desired

处理 MyMailConfiguration 时,无法保证 MailSenderAutoConfiguration 中的所有 bean 都已创建.所以 ConditionalOnBean 不起作用(bean 尚不存在).当没有 ConditionalOnBean anno 时,Spring 正确理解 bean 创建顺序图.

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);
    }

}

哪里RootConfig == MailSenderAutoConfiguration,RootMailer == JavaMailSender

whereRootConfig == MailSenderAutoConfiguration, RootMailer == JavaMailSender

生成输出:

MyConfig processed
RootConfig processed
Root bean created
MyMail bean created

如果取消@ConditionalOnBean 的注释,顺序将保持不变,但在 anno 处理时刻该 bean 将不存在.

If you uncomment @ConditionalOnBean the order will remain the same, but the bean will not exist at the anno processing moment.

这篇关于Spring boot - 仅当 bean JavaMailSender 存在时自动配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 14:34