004——Spring中Bean的初始化和销毁

Bean的初始化有三种方法:

  • 通过<bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法
  • 如果在上下文中定义的很多Bean都拥有相同名字的初始化方法和销毁方法,使用<beans>元素的default-init-method/default-destroy-method
  • 通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法
package com.java.spring;

public class InitAndDestroy {

	public void init() {
		System.out.println("bean was born");
	}
	
	public void destroy() {
		System.out.println("bean was dead");
	}
	
	public void coming() {
		System.out.println("|I am coming");
	}
}

package com.java.spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class InitDestroy implements InitializingBean, DisposableBean {

	public void afterPropertiesSet() throws Exception {
		System.out.println("InitDestroy was born");
	}

	public void destroy() throws Exception {
		System.out.println("InitDestroy was dead");
	}

	public void coming() {
		System.out.println("I am coming");
	}
}
测试类:
package com.java.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Practice {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		InitDestroy id = (InitDestroy) ctx.getBean("InitDestroy");
		id.coming();
		((ClassPathXmlApplicationContext) ctx).close();//关闭应用上下文容器
	}
	
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	     xmlns:aop="http://www.springframework.org/schema/aop"
	     xmlns:tx="http://www.springframework.org/schema/tx"
	     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
           default-init-method="init"
           default-destroy-method="destroy"
           >
       <!--     
      <bean id="initAnddestroy" class="com.java.spring.InitAndDestroy" />
       -->
      <!-- 
      <bean id="initAnddestroy" class="com.java.spring.InitAndDestroy" 
      		init-method="init" destroy-method="destroy"/>  
	  -->
      
      <bean id="InitDestroy" class="com.java.spring.InitDestroy" />  
           
</beans>




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值