Session类中的getDefaultInstance()和getInstance()有什么区别?

Session.getDefaultInstance(props, authenticator)getInstance(props, authenticator)什么区别? 一般来说,你何时会选择一个而不是另一个?

我还在getDefaultInstance(props,authenticator)上阅读了Java doc,但仍然无法清楚地清楚地看出差异。

希望专家可以帮助我更好地理解这一点。

更新:触发提出此问题的实际原因是:我们在基于Web的应用程序中的某些位置使用了Session.getDefaultInstance()方法。 有时,它抛出java.lang.SecurityException: Access to default session denied ,在快速谷歌搜索时,它建议使用Session.getInstance()方法。 因此,当一个人选择一个而不是另一个?

如果您阅读文档,您将看到

getDefaultInstance获取默认的Session对象。 如果尚未设置默认值,则会创建一个新的Session对象并将其安装为默认值。

因此,如果尚不存在,则调用getInstance()

getInstance获取一个新的Session对象。

因此,无论是否已存在,都会创建一个新的会话对象。

原因在javax.mail.Session.java中的getDefaultInstance方法中引发此错误。 根据此源代码,当默认会话对象已初始化,但更新或更改身份validation器实例,或默认会话对象的类加载器与参数authentificator不同时,会发生此错误。 也许使用java邮件的默认会话实例的java源代码被重新编译和重新加载,或者重复的javamail类库被包含在环境的Classpath中。 它提供了适当的解决方

 javax.mail.Session.java file public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator) { if (defaultSession == null) defaultSession = new Session(props, authenticator); else { // have to check whether caller is allowed to see default session if (defaultSession.authenticator == authenticator) ; // either same object or both null, either way OK else if (defaultSession.authenticator != null && authenticator != null && defaultSession.authenticator.getClass().getClassLoader() == authenticator.getClass().getClassLoader()) ; // both objects came from the same class loader, OK else // anything else is not allowed throw new SecurityException("Access to default session denied"); } return defaultSession; } 

对我来说,使用getInstance()而不是getDefaultInstance()非常重要。

因为邮件会话属性更改后,邮件会话仍然存储旧属性。

所以getDefaultInstance() – 它看起来像Singleton。

正如文档所说:

另请注意,在创建新的Session对象时,仅在第一次调用此方法时才使用Properties对象。 后续调用返回第一次调用创建的Session对象,并忽略传递的Properties对象。 每次调用方法时,使用getInstance方法获取新的Session对象。

常见问题解答说: https : //javaee.github.io/javamail/FAQ#getdefaultinstance

问:我何时应该使用Session.getDefaultInstance ,何时应该使用Session.getInstance

答:几乎所有代码都应该使用Session.getInstanceSession.getDefaultInstance方法使用传递的Properties在第一次调用时创建一个新的Session。 后续调用将返回原始会话并忽略您传入的任何属性。如果要创建具有不同属性的不同会话,Session.getDefaultInstance将不会这样做。 如果同一JVM中的某些其他代码(例如,在同一个应用程序服务器中)已经使用其属性创建了默认会话,则最终可能会使用其会话,并且您的属性将被忽略。 这通常可以解释为什么您的属性设置似乎被忽略。 始终使用Session.getInstance来避免此问题。