When does Spring create instances of objects that are injected

此生再无相见时 提交于 2019-12-20 21:56:22

问题


Spring does DI and creates objects so that your program need not worry of creating objects. But the question here is when an instance of injected object is created. Is it when the main program makes use of the instance or at the time an instance of main program is created.


回答1:


All beans in the context are instantiated, injected and initialized when the context starts up. By the time the first bean has been retrieved from the context, all beans are ready for use.

There are two things that can prevent a bean being initialized at context start up:

  • A bean has bean configured with a different scope (such as prototype, request or session), using the scope="xyz" attribute
  • A bean has been marked with lazy-init="true", in which case it will only be instantiated when it's explicitly asked for, or if it's required as a dependency of some other bean.



回答2:


In a comment, the OP writes:

So it is up to the programmer to decide whether a bean needs to be lazily initialized or initialized upfront. This could be very subjective, but could you let me know about any best practices followed in this kind of situations.

Yes, it is up to the programmer (or system integrator) to decide.

There aren't really any "best practice" rules for deciding. Think of it this way:

  • If you declare a bean as lazily initialized when it will always need to be instantiated, you will possibly make the startup process slower.

  • If you declare a bean as eagerly initialized when it is not always needed, you will make the startup process slower, and possible use more memory. In the worst case, creating the unnecessary bean may even cause startup to fail.

In short, you need to understand your application.




回答3:


http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lazy-init

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.



来源:https://stackoverflow.com/questions/2084637/when-does-spring-create-instances-of-objects-that-are-injected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!