动态创建spring Bean -- javaMail, 实现srping javaMail邮件发送

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.*;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 动态创建JavaMail Bean
 *
 * Created by ChenYu on 2015/5/25.
 */
@Service
public class JavaMailBeanService implements ApplicationContextAware,ApplicationListener {

    private Logger logger = LoggerFactory.getLogger(JavaMailBeanService.class);

    private static ConfigurableApplicationContext  app;

    @Autowired
    private MessageEmailConfigDao configDao;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        // 如果是容器刷新事件OR Start Event
        if (applicationEvent instanceof ContextRefreshedEvent) {
            try {
                refJavaMail();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //WebApplicationContext
        this.app = (ConfigurableApplicationContext)applicationContext;
    }

    //查询数据库并刷新Bean
    public void refJavaMail() {

        List<MessageEmailConfig> emailConfig = (List<MessageEmailConfig>)configDao.findAll();
        if (CollectionUtils.isNotEmpty(emailConfig)) {
            addSourceBeanToApp(emailConfig.get(0));
            logger.info("邮箱初始化成功");
        } else {
            logger.info("邮箱初始化失败,缺少数据");
        }

    }


    private void addSourceBeanToApp(MessageEmailConfig emailConfig) {
        DefaultListableBeanFactory acf = (DefaultListableBeanFactory) app.getAutowireCapableBeanFactory();
        String MAIL_BEAN_CLASS = "org.springframework.mail.javamail.JavaMailSenderImpl";
        BeanDefinitionBuilder bdb;
        // 根据数据源得到数据,动态创建数据源bean 并将bean注册到applicationContext中去
        //	bean ID
        String beanKey = EmailUtilService.javaMailSender;
        //	创建bean
        Map<String,String> map = new HashMap<String,String>();
        map.put("mail.smtp.auth","true");
        bdb = BeanDefinitionBuilder.rootBeanDefinition(MAIL_BEAN_CLASS);
        bdb.getBeanDefinition().setAttribute("id", beanKey);
        bdb.addPropertyValue("host", emailConfig.getSmtpUrl());
        bdb.addPropertyValue("username", emailConfig.getValidateUsername());
        bdb.addPropertyValue("password", emailConfig.getValidatePassword());
        bdb.addPropertyValue("port", emailConfig.getSmtpPort());
        bdb.addPropertyValue("javaMailProperties",map);
        //	注册bean
        acf.registerBeanDefinition(beanKey, bdb.getBeanDefinition());
    }

}

动态创建javaMail注册到springBean容器, 如果更新数据库表的时候调用刷新 即可刷新 javaMail,


邮件发送:

 /**
     * 邮件发送
     * @param subject 主题
     * @param content 内容
     * @param recipients 收件人
     */
    public void sendEmail(String subject,String content, String... recipients) throws MessagingException {
        //从spring 容器里面取javaBean
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl)BeanUtil.getBean(javaMailSender);
        //创建mime
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,"UTF-8");
            //设置收件人
            messageHelper.setTo(recipients);
            //设置发件人
            messageHelper.setFrom(mailSender.getUsername());
            //设置主题
            messageHelper.setSubject(subject);
            //设置发送内容
            messageHelper.setText(content, true);
            mailSender.send(mimeMessage);
            logger.info("邮件发送成功!发件人:"+mailSender.getUsername()+"收件人:"+ Arrays.toString(recipients)+"主题:"+subject+"内容:"+content);
    }


你可能感兴趣的:(spring,javamail,动态创建Bean)