將郵件會話(javax.mail.Session)存儲在單例中是一種很好的做法嗎?我和我的團隊決定在Singleton類中的一個靜態變量中保留單個郵件會話。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);
}
但我很擔心,如果是最好的保持它這樣或打開和關閉會話的每個電子郵件。
關於「singleton」+「好習慣」:將鼠標懸停在[singleton]標籤上並閱讀[info](http://stackoverflow.com/tags/singleton/info)文本或[this](http: /sourcemaking.com/design_patterns/singleton)或觀看[this](http://www.youtube.com/watch?v=-FRm3VPhseI)。 – zapl