I have a bean defined in my spring web application and I expect to have only one instance of this bean, here is my bean definition:
<bean id="accessControl" class="my.spring.app.AccessControl" />
In the AccessControl constructor, I assign an identifier to an object, something like this:
public class AccessControl { private long id = 0; public AccessControl() { id = System.currentTimeMillis(); } public long getAccessControlId() { return id; } }
In another class, I'm trying to get an AccessControl instance, something like this:
ApplicationContext ctx = new ClassPathXmlApplicationContext("acbean.xml"); AccessControl ac = (AccessControl) ctx.getBean("accessControl"); LOGGER_.info("AccessControl Identifier : " + ac.getAccessControlId());
I expect the id value to be the same because the id value is set in the constructor, and the constructor should not be called again and again, but this is exactly what happens. Infact, I added a log statement to the constructor, and every new object is created every time.
I 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 that defined twice with two different bean identifiers, and the application context is the same.
Can someone share what is not the way I defined a bean?
I also experimented with singleton = "true" and scope = "singleton", but they are not different.
Thanks.
source share