将邮件会话 (javax.mail.Session) 存储在单例中是一种好习惯吗?我和我的团队决定在 Singleton 类的静态变量中保留一个邮件会话。
因此,在私有构造函数中,我们这样做:
try {
Properties props = new Properties();
props.put("mail.transport.protocol", config.getMailTransportProtocol());
props.put("mail.smtp.starttls.enable", config.getMailStarttlsEnable());
props.put("mail.smtp.host", config.getMailHost());
props.put("mail.smtp.auth", config.getMailAuth());
props.put("mail.smtp.user", config.getMailFrom());
props.put("mail.debug", config.getMailDebug());
props.put("mail.smtp.port", config.getMailPort());
props.put("mail.smtp.socketFactory.port", config.getMailPort());
props.put("mail.smtp.socketFactory.class", config.getMailSocketFactoryClass());
props.put("mail.smtp.socketFactory.fallback", config.getMailSocketFactoryFallback());
props.put("mail.pop3.host", config.getMailPop3Host());
props.put("mail.store.protocol", config.getMailStoreProtocol());
SimpleAuth auth = new SimpleAuth(config.getMailUser(), config.getMailPass());
MailSession.session = Session.getDefaultInstance(props, auth);
session.setDebug(config.getMailDebug());
} catch (Throwable ex) {
System.err.println("Initial MailSession creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
但我担心最好是保持这种状态,还是为每封电子邮件打开和关闭一个会话。