Spring 提供了两种方式在Bean 的全部属性设置成功后执行特定的行为:
1.使用init-method属性
2.使用InitializingBean 接口,该接口提供了一个方法:void afterPropertiesSet() throws Exception (在Bean中实现)
如果两种都设了,先执行InitializingBean接口中 的,后执行init-method属性指定的方法
public class Chinese
implements Person,InitializingBean
{
private Axe axe;
public Chinese()
{
System.out.println("Spring实例化主调bean:Chinese实例...");
}
//依赖注入必须的setter方法
public void setAxe(Axe axe)
{
System.out.println("Spring执行依赖关系注入...");
this.axe = axe;
}
public void useAxe()
{
System.out.println(axe.chop());
}
//测试用初始化方法
public void init()
{
System.out.println("正在执行初始化方法 init...");
}
//实现InitializingBean接口必须实现的方法
public void afterPropertiesSet() throws Exception
{
System.out.println("正在执行初始化方法 afterPropertiesSet...");
}
}bean.xml如下:
<?xml version="1.0" encoding="GBK"?> <!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 --> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/> <!-- 配置chinese Bean,使用init-method="init" 指定该Bean所有属性设置完成后,自动执行init方法 --> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese" init-method="init"> <property name="axe" ref="steelAxe"/> </bean> </beans>
原文:http://blog.csdn.net/fangchao3652/article/details/23960053