Java bean的作用域与生命周期

1.作用域

①singleton  spring中的单例是基于BeanFactory的,在容器中只有一个

    不管是否使用,容器里面都是同一个对象

<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

②prototype  从此从容器中获取bean,会返回一个新的实例

    一个bean对应多个实例,创建容器的时候并没有实例化,当获取的时候才去创建,并且每次获取的都不一样。

    所以无状态的bean使用单例,有状态的使用原型。

<bean id="test" class="com.foo.Default" scope="prototype"/>

or

<bean id="test" class="com.foo.Default" singleton="false"/> 

③request     每次http请求都会创建新的bean,仅适用于WebApplicationContext

    一个bean对应一个实例,但是每个请求都有各自的bean实例

<bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>

    并且每次http请求创建的loginAction bean只在当前请求内有效,并且相互之间隔离,一旦请求结束就销毁了。

④session     相同http session共享一个bean,不同的session则是不同bean,仅适用于WebApplicationContext

    同request,一个bean只有一个实例

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

   同request,创建的是userPreferences bean

⑤global session  portlet应用,仅适用于WebApplicationContext

   同request,一个bean只有一个实例

<bean id="user" class="com.foo.Preferences "scope="globalSession"/>

 仅仅在portlet应用中才有意义,它被所有构成某个portlet web应用的各种不同的portlet共享。

2.生命周期

图片来源https://www.zhihu.com/question/38597960?sort=created



①.实例化;

②.填充属性;

③.BeanNameAware,将Bean的ID传递给setBeanName()方法;

④.BeanFactoryAware,将调用setBeanDactory()方法并把BeanFactory容器实例作为参数传入;

⑤.ApplicationContextAware,调用setApplicationContext()方法,把应用上下文作为参数传入;

⑥.BeanPostProcess,调用postProcessBeforeInitialization方法(对bean进行修改等操作);

⑦.InitializingBean,调用afterPropertiesSet方法,初始化bean;

⑧.BeanPostProcess,调用postProcessAfterInitialization方法(对bean进行修改等操作);

⑨.bean将存活至上下文被销毁

⑩.DispostbleBean,调用destory方法,在Bean实例销毁前执行。

⑪.销毁完成

猜你喜欢

转载自blog.csdn.net/CUG_ZG/article/details/84552634