懒得笔记3 spring bean 的生存范围 生命周期

 1,生存范围

Scope Description

singleton

(Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

application

Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

 


bean 中scope 的属性 

  1, singleton  单例,默认值  ,不管new 多少次,取到的都是同一个对象。

    

                UserService service = (UserService)ctx.getBean("userService");
		UserService service2 = (UserService)ctx.getBean("userService");
		
		System.out.println(service == service2);//为true

2, prototype 原型  每次取到的不一样 struts 里面action 用这个 官方推荐,


2,生命周期

  默认情况下,每次启动都会将所有bean生成放在内存中。

  1,lazy-initialized  (一般不用到)

    context 声明时进行初始化,在get的时候再进行初始化

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.foo.AnotherBean"/>

设置所有的bean 

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>


2,

init-method destroy-methd 

不要和

prototype

一起用(了解)

 

init-method destroy-methd 

不要和

prototype

一起用(了解)

 

     init-method destroy-methd 不要和prototype一起用(了解)  

     两个属性可以在定义bean在初始化和destroy时调用的方法。


猜你喜欢

转载自blog.csdn.net/chen_xinjia/article/details/47613671
今日推荐