Bean基本管理的小细节

Spring使用BeanFactory、ApplicationContext来管理bean的生命周期,有如下特点:
1)默认情况下,定义文件中的bean都是Singleton的,即每次通过getBean()方法返回的对象都是同一个对象,可以通过Bean的scope指定为prototype、或者将singleton指定为false,

使得每次调用getBean()方法时都产生一个新对象,如:

 

<beans...>
<bean id="hello" class="com.spring.bean.HelloBean" scope="prototype"/>
<bean id="greet" class="com.spring.bean.HelloBean" singleton="false"/>
</bean>

 

但需要注意的是,这里的singleton是针对一个Ioc容器维护一个bean对象,即一个BeanFactory或ApplicationContext对象只维护一个bean对象,而不是设计模式中谈论到的Singleton模式,那是指一个ClassLoader只载入一个对象。

 

2)使用BeanFactory时,Bean对象是在调用getBean()方法时才被实例化的;而使用ApplicationContext时,默认情况下,当ApplicationContext对象被初始化时,所有的Bean都会被实例化,如果想要Bean在getBean()方法被调用时才实例化,需要在<bean>标签中将lazy-init属性设置为true,如:

 

<bean id="date" class="java.util.Date" lazy-init="true"/>

 

3)Bean定义的继承。当应用中有多个对象拥有相同属性、且属性值在初始化时需要有相同的值,那么可以通过Bean定义的继承来减少配置,如:

 

<beans...>

<bean id="parent" abstract="true">
<property name="name" value="default"/>
<property name="id" value="0"/>
</bean>

<bean id="user" class="com.spring.User" parent="parent">
<property name="age" value="12"/>
</bean>

</beans>

  

通过abstract="true",将一个Bean定义为抽象Bean,这样BeanFactory或ApplicationContext就不会初始化它,然后在其它Bean中将parent属性指定为parent,表示这个Bean的name和id属性将继承至parent中。子类定义的同名属性将覆盖父类中的同名属性。

除了可以继承自抽象Bean,也可以继承自实例Bean,如:

 

<beans...>

<bean id="parent" class="com.spring.User">
<property name="name" value="default"/>
<property name="id" value="0"/>
</bean>

<bean id="user" class="com.spring.User" parent="parent">
<property name="age" value="12"/>
<property name="name" value="jojo"/>
</bean>

</beans>

 

 

 

 

 

 

 

 

你可能感兴趣的:(设计模式,spring,bean,prototype,配置管理)