bean的范围由<bean>的scope
属性决定,可选值:singleton
、request、session、websocket、application,默认singleton
The scope of this bean: typically “singleton” (one shared instance, which will be returned by all calls to getBean with the given id), or “prototype” (independent instance resulting from each call to getBean). By default, a bean will be a singleton, unless the bean has a parent bean definition in which case it will inherit the parent’s scope. Singletons are most commonly used, and are ideal for multi-threaded service objects. Further scopes, such as “request” or “session”, might be supported by extended bean factories (e.g. in a web environment). Inner bean definitions inherit the scope of their containing bean definition, unless explicitly specified: The inner bean will be a singleton if the containing bean is a singleton, and a prototype if the containing bean is a prototype, etc.
bean的scope属性:典型的是singleton(一个共享的实例,所有针对该bean的调用都返回该实例),或者prototype(每次调用返回一个新实例)。默认是singleton,除非父bean已经定义了一个scope值,这样则会继承该值。singleton是最常用的,而且在多线程服务中是比较适合的。内部类继承外部类的scope属性值,除非特别指定
【singleton】
singleton范围bean实例的范围仅限于Spring容器实例,在多个容器中也不是单例的
在默认情况下,singleton范围的bean是预先实例化的,这意味着在创建Spring容器实例的时候,将会创建singleton范围bean的实例。
- 可以通过设置
init-lazy="true"
来让singleton范围的bean延迟初始化,当第一次请求的时候才创建bean实例 - 也可以通过使用
<beans>
的default-lazy-init
来指定程序上下文中bean的默认策略,当与bean自己策略冲突时,会采用bean自己的策略 - 在大多数场景中,创建容器的时候就初始化实例有助于及早发现配置问题
【prototype】
每次调用都会返回一个新实例。prototype的bean总是延迟初始化
如果一个bean不会保持任何会话状态(也就是说它是无状态的),那么它应该定义为一个singleton。
如果一个bean保持会话状态,它应该定义一个prototype。