【问题标题】:Spring singleton class creating multiple instanceSpring单例类创建多个实例
【发布时间】:2020-05-27 10:40:22
【问题描述】:

我正在尝试将类设置为单例,并使其在以下更改完成

 Beans.xml has this:

 <bean id="LdapUti" class="com.amazon.bpmsawsproxy.util.LdapUtil" scope="singleton" />

 LdapUtil class:

public class LdapUtil {
     private static Log logger = LogFactory.getLog(LdapUtil.class);

     public DirContext GetLdapDirContext() throws NamingException {

        Hashtable<String, Object> env = new Hashtable<String, Object>(11);
         env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

         env.put(Context.PROVIDER_URL, "*********");

         env.put(Context.SECURITY_CREDENTIALS, "******");
         env.put(Context.SECURITY_PROTOCOL, "ssl");
         env.put(Context.SECURITY_AUTHENTICATION, "simple");

         DirContext ctx = new InitialLdapContext(env, null);
         return ctx;}}

这是为测试单例类而编写的单元测试用例

       @Test
public void testSingleton(){
    LdapUtil ctx1 = new LdapUtil();

    LdapUtil ctx2 = new LdapUtil();

    assertEquals(System.identityHashCode(ctx1), System.identityHashCode(ctx2));

}

从单元测试用例:我得到两个不同的哈希码,我相信它创建了多个实例。如果我错过了什么,请告诉我

【问题讨论】:

    标签: spring singleton spring-framework-beans


    【解决方案1】:

    请注意不是单例中的类,仅在 sping config xml 中将类的范围设置为单例。

    您创建了不受 spring 管理的新实例,因此您获得了不同的哈希码。

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多