I was wondering how the lifecycle of a singleton bean (annotated with @Scope(value="singleton")) in Spring is exactly defined.
Specifically, is it guaranteed that within the same ApplicationContext consecutive lookups of that bean return the same bean object instance?
Yes, that is the definition of
singletonscope: only one instance returned by every call togetBean(). Note that non-lazysingletonis the default scope in Spring.Also if singleton is defined as lazy and no other non-lazy bean references it, it will be created during first explicit lookup.
EDIT: To answer your comment: occasionally you might discover that your singleton is created twice. Take this bean as an example:
Even though this is a singleton, your program might produce the following output:
Constructor has been called twice – once for the original class and second time for the class created by CGLIB to implement proxying on a class without any interfaces. To preserve
Singletonpublic interface, the class generated by CGLIB must subclass from the original class. This way CGLIB class might be used whereSingletonwas expected (polymorphism). But subclass must call the base class constructor, hence two constructor calls.But don’t worry, the CGLIB-generated class is just a stub that redirects all the calls to a “normal” bean, applying AOP stuff in the meantime.