您的位置:首页 > 编程语言 > Java开发

spring使用注解让bean创建多个实例

2017-09-13 16:51 621 查看
spring使用bean默认是单实例singleton模式,如果要想创建多个实例要在类上添加注解

@Scope(value = "prototype")

但是这个时候,它所注入的那个类如果是单实例模式的话,那么在那个类中它还是同一个实例,比如写的这个邮件的工具类,发邮件的时候会对密码(password属性)进行解密,如果是单实例,第一次解密了,第二次再调用的时候,解密就会失败报错,这里有三种解决方案:

第一种:在它要注入的那个类上也使用@Scope(value = "prototype")注解。

第二种:这个注解改为:

@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)

/*
* Copyright (c) 2017 www.bsfit.com.cn All Rights Reserved.
*/
package cn.com.bsfit.frms.mt.mail;

import cn.com.bsfit.frms.portal.util.AESEncodeUtil;
import cn.com.bsfit.frms.portal.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
* The type Mail tool.
*
* @author: YeJunwei Date: 2017/8/4 Time: 14:59
*/
@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MailTool {
private Logger log = LoggerFactory.getLogger(MailTool.class);
@Value("${mail.smtp.host:smtp.exmail.qq.com}")
private String host;//smtp服务器地址
@Value("${mail.smtp.auth:true}")
private String auth;//是否需要认证
@Value("${mail.username:waf-bs@bsfit.cn}")
private String from;//发件人邮箱
@Value("${mail.password:91001573CC0F5FB08B6F7CEBF0DD152F}")//Bs12345678
private String password;//密码

/**
* Send mail boolean.
*
* @param to          the to 收件人
* @param cc          the cc 抄送
* @param subject     the subject 主题
* @param content     the content 内容
* @param attachments the attachments 附件
* @return the boolean
*/
public boolean sendMail(String to, String cc, String subject, String content, List<File> attachments) {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties();                    // 参数配置
props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", host);   // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", auth);            // 需要请求认证
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getDefaultInstance(props);
session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
//整封邮件的MINE消息体
MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系
if (!StringUtils.isEmpty(content)) {
MimeBodyPart contentPart = new MimeBodyPart();
try {
contentPart.setText(content);
msgMultipart.addBodyPart(contentPart);
} catch (MessagingException e) {
log.error("创建邮件主体失败", e);
return false;
}
}
if (null != attachments && attachments.isEmpty()) {
for (File attachment : attachments) {
MimeBodyPart filePart = new MimeBodyPart();
DataSource fileDataSource = new FileDataSource(attachment);
DataHandler dh = new DataHandler(fileDataSource);
try {
filePart.setDataHandler(dh);
filePart.setFileName(MimeUtility.encodeText(attachment.getName()));
msgMultipart.addBodyPart(filePart);
} catch (Exception e) {
log.error("添加附件失败", e);
return false;
}
}
}
try {
message.setFrom(new InternetAddress(from, "工单管理 ", "UTF-8"));
message.setRecipients(MimeMessage.RecipientType.TO, to);
if (!StringUtils.isEmpty(cc)) {
message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(cc));
}
message.setContent(msgMultipart);
message.setSentDate(new Date());
message.setSubject(subject, "UTF-8");
message.saveChanges();
} catch (Exception e) {
log.error("创建邮件失败", e);
return false;
}
try {
// 4. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
//
//    PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
//           仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
//           类型到对应邮件服务器的帮助网站上查看具体失败原因。
//
//    PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
//           (1) 邮箱没有开启 SMTP 服务;
//           (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
//           (3) 邮箱服务器要求必须要使用 SSL 安全连接;
//           (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
//           (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
//
//    PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
password = AESEncodeUtil.decrypt(password, Constants.AES_KEY);
transport.connect(from, password);

// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
} catch (Exception e) {
log.error("发送邮件失败", e);
return false;
}
return true;
}
}

第三种:使用@PostConstruc初始化的时候对密码进行解密

/*
* Copyright (c) 2017 www.bsfit.com.cn All Rights Reserved.
*/
package cn.com.bsfit.frms.mt.mail;

import cn.com.bsfit.frms.portal.util.AESEncodeUtil;
import cn.com.bsfit.frms.portal.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
* The type Mail tool.
*
* @author: YeJunwei Date: 2017/8/4 Time: 14:59
*/
@Component
public class MailTool {
private Logger log = LoggerFactory.getLogger(MailTool.class);
@Value("${mail.smtp.host:smtp.exmail.qq.com}")
private String host;//smtp服务器地址
@Value("${mail.smtp.auth:true}")
private String auth;//是否需要认证
@Value("${mail.username:waf-bs@bsfit.cn}")
private String from;//发件人邮箱
@Value("${mail.password:91001573CC0F5FB08B6F7CEBF0DD152F}")//Bs12345678
private String password;//密码

@PostConstruct
public void decryptPassword() {
this.password = AESEncodeUtil.decrypt(password, Constants.AES_KEY);
}

/**
* Send mail boolean.
*
* @param to          the to 收件人
* @param cc          the cc 抄送
* @param subject     the subject 主题
* @param content     the content 内容
* @param attachments the attachments 附件
* @return the boolean
*/
public boolean sendMail(String to, String cc, String subject, String content, List<File> attachments) {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties();                    // 参数配置
props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", host);   // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", auth);            // 需要请求认证
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getDefaultInstance(props);
session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
//整封邮件的MINE消息体
MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系
if (!StringUtils.isEmpty(content)) {
MimeBodyPart contentPart = new MimeBodyPart();
try {
contentPart.setText(content);
msgMultipart.addBodyPart(contentPart);
} catch (MessagingException e) {
log.error("创建邮件主体失败", e);
return false;
}
}
if (null != attachments && attachments.isEmpty()) {
for (File attachment : attachments) {
MimeBodyPart filePart = new MimeBodyPart();
DataSource fileDataSource = new FileDataSource(attachment);
DataHandler dh = new DataHandler(fileDataSource);
try {
filePart.setDataHandler(dh);
filePart.setFileName(MimeUtility.encodeText(attachment.getName()));
msgMultipart.addBodyPart(filePart);
} catch (Exception e) {
log.error("添加附件失败", e);
return false;
}
}
}
try {
message.setFrom(new InternetAddress(from, "工单管理 ", "UTF-8"));
message.setRecipients(MimeMessage.RecipientType.TO, to);
if (!StringUtils.isEmpty(cc)) {
message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(cc));
}
message.setContent(msgMultipart);
message.setSentDate(new Date());
message.setSubject(subject, "UTF-8");
message.saveChanges();
} catch (Exception e) {
log.error("创建邮件失败", e);
return false;
}
try {
// 4. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
//
//    PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
//           仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
//           类型到对应邮件服务器的帮助网站上查看具体失败原因。
//
//    PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
//           (1) 邮箱没有开启 SMTP 服务;
//           (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
//           (3) 邮箱服务器要求必须要使用 SSL 安全连接;
//           (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
//           (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
//
//    PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
transport.connect(from, password);

// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
} catch (Exception e) {
log.error("发送邮件失败", e);
return false;
}
return true;

3ff0
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring
相关文章推荐