转自:http://www.blogjava.net/cmzy/archive/2008/07/29/218059.html
- /**
- *
- */
- package ioc.test;
- /**
- * @author zhangyong
- *
- */
- public class Animal{
- private String name;
- private int age;
- public String speak(){
- return "我的名字:"+this.name+",我的年龄:"+this.age;
- }
- public void init_xx() throws Exception {
- System.out.println("初始化方法start()正在运行!");
- }
- public void end() throws Exception {
- System.out.println("析构方法end()正在运行!");
- }
- //Geter和Seter省略
- }
配置文件中配置好bean,并为其指定响应的预处理方法和析构方法:
这里的init_xx方法在实例化与依赖注入之前被调用,end方法在销毁之前调用
- <?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.5.xsd">
- <bean id="animal" class="ioc.test.Animal" init-method="init_xx" destroy-method="end">
- <property name="age" value="5"></property>
- <property name="name" value="猪"></property>
- </bean>
- </beans>
创建含有主方法的测试类,代码如下:
- /**
- *
- */
- package ioc.test;
- import org.springframework.context.support.AbstractApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * @author zhangyong
- *
- */
- public class TestMain {
- public static void main(String[] args) {
- AbstractApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
- //注册容器关闭钩子,才能关掉容器,调用析构方法
- ac.registerShutdownHook();
- Animal animal =ac.getBean("animal",Animal.class);
- System.out.println(animal.speak());
- }
- }
运行主类,结果如下:
需要注意的是:要看到析构方法的输出,也必须要注册关闭钩子。