依赖关系注入之后的行为

    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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值