您的位置:首页 > 编程语言 > Java开发

Spring Bean的配置项及作用域

2017-03-25 20:21 260 查看

singleton:单例,指一个Bean容器中只存在一份(默认)

prototype:每次请求(每次使用)创建新的实例,destroy方式不生效

request:每次http请求创建一个实例且仅在当前request内有效

session:同上,每次http请求创建,当前session内有效

global session:基于portlet的web有效(portlet定义了global session),如果是在web中,同session

singleton:


<bean id="Ipeople" class="com.practice.entity.PeopleImp" scope="singleton">
<!--   <property name="cup" ref="icupblue"></property>
<property name="cup1" ref="icupblack"></property> -->
<constructor-arg ref="icupblue" index="0"></constructor-arg>
<constructor-arg ref="icupblack" index="1"></constructor-arg>
<constructor-arg value="ye" index="2"></constructor-arg>
</bean>


prototype:



<bean id="Ipeople" class="com.practice.entity.PeopleImp" scope="prototype">
<!--   <property name="cup" ref="icupblue"></property>
<property name="cup1" ref="icupblack"></property> -->
<constructor-arg ref="icupblue" index="0"></constructor-arg>
<constructor-arg ref="icupblack" index="1"></constructor-arg>
<constructor-arg value="ye" index="2"></constructor-arg>
</bean>






Bean的初始化与销毁:

通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;

通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法

在指定方法上加上@PostConstruct或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。

4.

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd" default-init-method="defaultinit" default-destroy-method="defaultdestroy">

这种方式在bean中可以选择使用,可选择不使用。


配置init-method/destroy-method属性:

<bean id="icupblack" class="com.practice.entity.PaperCup" init-method="start" destroy-method="stop">
<property name="color" value="black"></property>
</bean>


执行顺序:实现InitializingBean/DisposableBean 接口>配置init-method/destroy-method属性

当一个bean实现了InitializingBean/DisposableBean 接口或配置了init-method/destroy-method属性,default-init-method=”defaultinit” default-destroy-method=”defaultdestroy”这种方式的初始化不生效,会被覆盖掉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: