Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring singleton created multiple times

I have a bean defined in my spring web application and I am expecting to have only one instance of this bean, here is my bean definition:

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

In the constructor of AccessControl, I assign an identifier to the object, something like this:

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

   public long getAccessControlId() {
        return id;
   }
}

In a different class, I try to get hold of the instance of AccessControl, something like this:

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

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

I am expecting the "id" value to be the same because the value of "id" is set in the constructor and constructor should not get called again and again but that is exactly what is happening. Infact, I added a log statement to the constructor and a new object is created everytime.

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

Can anyone share what is wrong with the way I have defined the bean?

I have also experimented with singleton="true" and scope="singleton" but they do not make any differece.

Thanks.

like image 550
user305210 Avatar asked Oct 27 '11 19:10

user305210


1 Answers

the singelton-ness in spring is per application context, every time you create a new instance of the application context (like the first line in your second code sample) all the singletons are instantiated.

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

like image 81
LiorH Avatar answered Sep 24 '22 08:09

LiorH