加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

依赖关系注入之后的行为

发布时间:2020-12-13 23:03:51 所属栏目:百科 来源:网络整理
导读:Spring 提供了两种方式在Bean 的全部属性设置成功后执行特定的行为: 1.使用init-method属性 2.使用InitializingBean 接口,该接口提供了一个方法:void afterPropertiesSet() throws Exception (在Bean中实现) 如果两种都设了,先执行InitializingBean接

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读