Spring 4 mail configuration via java config

前端 未结 2 1456
日久生厌
日久生厌 2021-01-17 19:03

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:



        
相关标签:
2条回答
  • 2021-01-17 19:20

    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

    0 讨论(0)
  • 2021-01-17 19:35
    @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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题