Java – spring singleton has been created many times

I have defined a bean in my spring web application. I want only one instance of this bean. This is my bean definition:

<bean id="accessControl" class="my.spring.app.AccessControl" />

In the constructor of accesscontrol, I assign an identifier to the object, as shown below:

public class AccessControl {
   private long id = 0;
   public AccessControl() {
        id = System.currentTimeMillis();
   }

   public long getAccessControlId() {
        return id;
   }
}

In another class, I try to grab an instance of accesscontrol, as shown below:

ApplicationContext ctx =
                     new ClassPathXmlApplicationContext("acbean.xml");

            AccessControl ac = (AccessControl) ctx.getBean("accessControl");
            LOGGER_.info("AccessControl Identifier : " + ac.getAccessControlId());

I expect the value of "Id" to be the same, because the value of "Id" is set in the constructor, and the constructor should not be called again and again, but that's what happens In fact, I added a log statement to the constructor, creating a new object each time

I saw it: http://www.digizenstudio.com/blog/2006/09/14/a-spring-singleton-is-not-a-singleton/ But I don't think I'm dealing with the same class defined twice with two different bean identifiers, and the application context is the same

Anyone can share the way I define beans. What's the problem?

I have also tried singleton = "true" and scope = "Singleton", but they are no different

thank you.

Solution

The singleton ness in spring refers to each application context. Each time a new instance of the application context is created (such as the first line in the second code example), all singletons will be instantiated

You need to have a single application context and reuse it in your application

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>