tags:

views:

104

answers:

2

I see that it initializes prototype beans on initial startup. How to prevent this ?

+4  A: 

This 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.

skaffman
@skaffman no. I have a reference from a prototype to a singleton. So singleton is a property of a prototype. Both are initialized, though, that singleton should be, and I cannot see any need to initialize a prototype at once. Still it happens.
EugeneP
2 ideas... use the eclipse spring plugin to get a map of your bean dependencies so that you can see if it is depended on by another singleton, also put a break point in the constructor of your prototype bean so that you can look at what is causing its instantiation.
Michael Wiles
@EugeneP: You're doing *something* trigger the init of the protoype. I'm telling you, Spring will *not* automatically initialize prototypes at startup.
skaffman
@skaffman Yes probably something triggers it. Ok what about "session" scope in a web-app? Is not it also initialized on start-up?
EugeneP
@EugeneP: All non-singletons beans are initialized only when they are first *referenced*. The starting of an HTTP session will not immediately initialize the session-scoped beans.
skaffman
+2  A: 

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.

Espen