Spring什么时候创建注入对象的实例 [英] When does Spring create instances of objects that are injected

查看:205
本文介绍了Spring什么时候创建注入对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring执行DI并创建对象,这样您的程序就不必担心创建对象了。
但这里的问题是何时创建了一个注入对象的实例。是在主程序使用实例时还是在创建主程序实例时。

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.

推荐答案

上下文启动时,上下文中的所有bean都会被实例化,注入和初始化。当从上下文中检索第一个bean时,所有bean都可以使用了。

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.

有两件事可以防止bean在上下文启动时被初始化:

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


  • bean的bean配置了不同的范围(例如 prototype request session ),使用 scope =xyz属性

  • bean已标记为 lazy-init =true ,在这种情况下,它只会在明确要求时实例化,或者如果需要将其作为其他bean的依赖项。

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

这篇关于Spring什么时候创建注入对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆