How to allow Spring to initialize "prototype" beans only when it is received through getBean ()?

I see that it initializes the beans prototype the first time it starts. How to prevent this?

+4
source share
2 answers

This is not true, objects with the beans prototype are not initialized at startup, unless something else refers to them.

If you find this to happen, you should have a link from a singleton bean to a protoype bean, and initializing a singleton bean will start creating a prototype.

+8
source

As Scuffman says in his post, the beans prototype is not initialized at startup.

Even this bean prototype configured with lazy-init set to false is not created before the ApplicationContext.getBean(..) method is executed.

 <bean id="demo" class="demo.Demo" scope="prototype" lazy-init="false"> 

Just add the debug log message to the bean constructor or run your debugger and you will see it yourself.

If you got your bean prototype as follows:

 Demo demo = context.getBean("demo", Demo.class); 

Then there is absolutely no chance that it is initialized when the container starts.

If you still have problems looking forward to initializing a bean with the prototype scope, I suggest you show a code that interacts with the Spring container and the Spring configuration.

The situation when the bean prototype will be initialized when the container starts (until your bean is configured using lazy-init="true" ):

 SingletonBean singletonBean = context.getBean(SingletonBean.class); Demo demo = singletonBean.getDemo(); 

If a singleton bean has a prototype bean, the prototype bean will be initialized along with a singleton bean.

Another side effect when retrieving a demo object through a singletonBean is that you will only have one demo object, no matter how many times you execute the context.getBean(SingletonBean.class); method context.getBean(SingletonBean.class); .

+2
source

Source: https://habr.com/ru/post/1309562/


All Articles