Spring 4 mail configuration via java config

回眸只為那壹抹淺笑 提交于 2019-12-01 14:56:23

问题


Is there some example of how MailSender can be configured via java config? All examples that I've seen uses xml to create needed beans:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
   <property name="host" value="mail.mycompany.com"/>
</bean>

<!-- this is a template message that we can pre-load with default state -->
 <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
 <property name="from" value="customerservice@mycompany.com"/>
 <property name="subject" value="Your order"/>
</bean>

回答1:


The code you posted (along with some small improvements to make it more configurable) would be transformed into the following Java config:

@Configuration 
public class MailConfig {

    @Value("${email.host}")
    private String host;

    @Value("${email.from}")
    private String from;

    @Value("${email.subject}")
    private String subject;

    @Bean
    public JavaMailSender javaMailService() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);
        return javaMailSender;
    }

    @Bean
    public SimpleMailMessage simpleMailMessage() {
       SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
       simpleMailMessage.setFrom(from);
       simpleMailMessage.setSubject(subject);
       return simpleMailMessage;
    }
}

You should also be aware of the fact that Spring Boot (which you have not mentioned whether or not you are using) can auto-configure an JavaMailSender for you. Check out this part of the documentation




回答2:


@Configuration 
public class AppConfig {

    @Value("${mail.host}")
    private String host;


    @Bean
    public JavaMailSender emailService() {
        JavaMailSender javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);
        return javaMailSender;
    }



@Component
public class EmailServiceImpl implements EmailService {

    @Autowired
    public JavaMailSender emailSender;

    public void sendSimpleMessage( String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage(); 
        message.setTo(to); 
        message.setSubject(subject); 
        message.setText(text);
        emailSender.send(message);
    }
}


来源:https://stackoverflow.com/questions/24097131/spring-4-mail-configuration-via-java-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!