I see that it initializes prototype beans on initial startup. How to prevent this ?
views:
104answers:
2This is not true, prototype-scoped beans are not initialized on startup, unless something else has a reference to them.
If you find that this is happening, then you must have a reference from a singleton bean to a protoype bean, and the initialization of the singleton bean is triggering the creation of the prototype.
As Skaffman says in his post, prototype beans are not initialized on startup.
Even this prototype bean that's configured with lazy-init set to false isn't created before the ApplicationContext.getBean(..)
method is executed.
<bean id="demo" class="demo.Demo" scope="prototype" lazy-init="false">
It's just to add a debug log message to your bean's constructor or start your debugger, then you will see it yourself.
If you receive your prototype bean like this:
Demo demo = context.getBean("demo", Demo.class);
Then it's absolutely no chance that it's initialized at container startup.
If you still have issues with eagerly initializing of bean with prototype scope, I suggest you show the code that interacts with the Spring container and the Spring configuration.
A situation where the prototype bean will be initialized when the container starts up (as long as your bean isn't configured with lazy-init="true"
):
SingletonBean singletonBean = context.getBean(SingletonBean.class);
Demo demo = singletonBean.getDemo();
When a singleton bean has a prototype bean dependency, the prototype bean will be initialized together with the singleton bean.
Another side effect with retrieving the demo object through the singletonBean is that you will only have one demo object no matter how many times you're executing the context.getBean(SingletonBean.class);
method.