在Spring中,Bean的生命週期包括Bean的定義,Bean的初始化,Bean的使用,Bean的銷燬。
Bean的定義
Bean的定義就是在XML進行相關配置,下面給出某個bean的定義
<bean id="HelloWorld" class="com.jeysine.test.HelloWorld">
<property name="msg">
<value>HelloWorld</value>
</property>
</bean>
Bean的初始化
在Spring中,有兩種初始化方式:
1. 通過init-method屬性完成
2. 實現org.springframework.beans.factory.InitializingBean接口
(1)init-method初始化
//HelloWord.java
import java.util.Date;
public class HelloWorld{
private String msg = null;
private Date date = null;
public init(){
this.msg = "HelloWorld";
this.date = new Date();
}
//set get方法省略
}
xml 配置
<bean id="HelloWorld" class="com.jeysine.test.HelloWorld" init-method="init" />
(2)實現InitialzingBean接口,實現該接口時,必須增加方法 afterPropertiesSet() 完成初始化工作。
//HelloWord.java
import java.util.Date;
import org.springframework.beans.factory.InitializingBean;
public class HelloWorld implement InitializingBean{
private String msg = null;
private Date date = null;
public afterPropertiesSet(){
this.msg = "HelloWorld";
this.date = new Date();
}
//set get方法省略
}
xml 配置
<bean id="HelloWorld" class="com.jeysine.test.HelloWorld" />
Bean的使用
Bean的使用有三種方式:
(1)使用BeanWrapper
HelloWorld helloWorld = new HelloWorld();
BeanWrapper bw = new BeanWrapperImpl(ihelloWorld);
bw.setPropertyValue("msg","HelloWorld");
System.out.println(bw.getPropertyValue("msg"));
(2)使用BeanFactory
InputStream is = new FileInputStream("config.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);
HelloWorld helloWorld = (HelloWorld)factory.getBean("HelloWorld");
System.out.println(helloWorld.getMsg());
(3)使用ApplicatonContext
ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml");
HelloWorld helloWorld = (HelloWorld)actx.getBean("HelloWorld");
System.out.println(helloWorld.getMsg());
小結:BeanWrapper不用到Spring的配置文件,而且只能對單個Bean進行設定,並不常有。而ApplicationContext 在BeanFactory的基礎上增加了更多的功能,故一般使用ApplicationContext 。
Bean的銷燬
Bean的銷燬有兩種方式:
- 通過destory-method指定
- 實現org.springframework.beans.factory.DisposableBean接口
(1)destory-method銷燬
//HelloWord.java
import java.util.Date;
public class HelloWorld{
private String msg = null;
private Date date = null;
public init(){
this.msg = "HelloWorld";
this.date = new Date();
}
public cleanup(){
this.msg = "";
this.date = null;
}
//set get方法省略
}
xml 配置
<bean id="HelloWorld" class="com.jeysine.test.HelloWorld" init-method="init" destroy-method="cleanup" />
(2)實現org.springframework.beans.factory.DisposableBean接口,實現該接口時,必須增加方法 destroy() 完成銷燬工作。
//HelloWord.java
import java.util.Date;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;
public class HelloWorld implement InitializingBean,DisposableBean {
private String msg = null;
private Date date = null;
public afterPropertiesSet(){
this.msg = "HelloWorld";
this.date = new Date();
}
public destroy(){
this.msg = "";
this.date = null;
}
//set get方法省略
}
xml 配置
<bean id="HelloWorld" class="com.jeysine.test.HelloWorld" />