一、Bean的定義
Spring通常通過配置文件定義Bean。如:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="HelloWorld" class="com.pqf.beans.HelloWorld">
<property name="msg">
<value>HelloWorld</value>
</property>
</bean>
</beans>
這個配置文件就定義了一個標識為 HelloWorld 的Bean。在一個配置文檔中可以定義多個Bean。
二、Bean的初始化
有兩種方式初始化Bean。
1、在配置文檔中通過指定init-method 屬性來完成
在Bean的類中實現一個初始化Bean屬性的方法,如init(),如:
public class HelloWorld{
public String msg=null;
public Date date=null;
public void init() {
msg="HelloWorld";
date=new Date();
}
......
}
然后,在配置文件中設置init-mothod屬性:
<bean id="HelloWorld" class="com.pqf.beans.HelloWorld" init-mothod="init" >
</bean>
2、實現 org.springframwork.beans.factory.InitializingBean接口
Bean實現InitializingBean接口,并且增加 afterPropertiesSet() 方法:
public class HelloWorld implement InitializingBean {
public String msg=null;
public Date date=null;
public void afterPropertiesSet() {
msg="向全世界問好!";
date=new Date();
}
......
}
那么,當這個Bean的所有屬性被Spring的BeanFactory設置完后,會自動調用afterPropertiesSet()方法對Bean進行初始化,于是,配置文件就不用指定 init-method屬性了。
三、Bean的調用
有三種方式可以得到Bean并進行調用:
1、使用BeanWrapper
HelloWorld hw=new HelloWorld();
BeanWrapper bw=new BeanWrapperImpl(hw);
bw.setPropertyvalue("msg","HelloWorld");
system.out.println(bw.getPropertyCalue("msg"));
2、使用BeanFactory
InputStream is=new FileInputStream("config.xml");
XmlBeanFactory factory=new XmlBeanFactory(is);
HelloWorld hw=(HelloWorld) factory.getBean("HelloWorld");
system.out.println(hw.getMsg());
3、使用ApplicationConttext
ApplicationContext actx=new FleSystemXmlApplicationContext("config.xml");
HelloWorld hw=(HelloWorld) actx.getBean("HelloWorld");
System.out.println(hw.getMsg());
四、Bean的銷毀
1、使用配置文件中的 destory-method 屬性
與初始化屬性 init-methods類似,在Bean的類中實現一個撤銷Bean的方法,然后在配置文件中通過 destory-method指定,那么當bean銷毀時,Spring將自動調用指定的銷毀方法。
2、實現 org.springframwork.bean.factory.DisposebleBean接口
如果實現了DisposebleBean接口,那么Spring將自動調用bean中的Destory方法進行銷毀,所以,Bean中必須提供Destory方法。