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

时间:2010-11-15 12:14:39

标签: java session javamail

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

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

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

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

4 个答案:

答案 0 :(得分:18)

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

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

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

<强>的getInstance 获取一个新的Session对象。

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

答案 1 :(得分:2)

原因 在javax.mail.Session.java中的getDefaultInstance方法中引发此错误。根据此源代码,当默认会话对象已经初始化,但更新或更改了身份验证器实例,或者默认会话对象的类加载器与参数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;
   }

答案 2 :(得分:2)

对我而言,使用 getInstance() 代替getDefaultInstance()非常重要。

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

所以getDefaultInstance() - 看起来像是Singleton。

正如文档所说:

  

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

答案 3 :(得分:2)

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

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

     

答:几乎所有代码都应使用Session.getDefaultInstance。该   Session.getInstance方法首先创建一个新的Session   使用传递的属性调用它的时间。随后   调用将返回原始会话并忽略您的任何属性   传入。如果你想创建不同的Sessions   属性,Session.getDefaultInstance不会这样做。如果其他一些   同一JVM中的代码(例如,在同一个应用服务器中)已经存在   创建默认会话及其属性,您可能最终   使用他们的会话,您的属性将被忽略。经常这样   解释了为什么您的属性设置似乎被忽略。 始终使用   {{1}}以避免此问题。