在bean中加入init-method , 和destory-method
测试类:
关闭容器,执行销毁的方法。
2.实现InitializingBean, DisposableBean接口
public class HelloSpring implements InitializingBean,DisposableBean {
private String hello ;
public HelloSpring() {
System.out.println("构造对象了...");
}
public void setHello(String hello) {
System.out.println("注入了一个Hello的属性..." + hello);
this.hello = hello;
}
@Override
public void destroy() throws Exception {
System.out.println("被卸载了...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("属性设置之后调用...");
}
public void init() {
System.out.println("init方法...");
}
public void disposable() {
System.out.println("disposable方法");
}
}
<bean name="helloSpring" class="com.csi.bean.HelloSpring" init-method="init" destroy-
method="disposable">
<property name="hello" value="今天天气好晴朗" />
</bean>
测试类
package com.csi.bean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestHelloSpring {
@Test
public void showHelloSpring() {
//步骤1:需要先加载Spring核心配置文件
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
//步骤2:需要获取到bean的id名称,也就是获取到由容器创建的对象
HelloSpring helloSpring = (HelloSpring) ctx.getBean("helloSpring");
System.out.println(helloSpring);
//使用注册关闭钩子。在虚拟机退出之前回调此函数,关闭容器
ctx.registerShutdownHook();
//步骤3:输出结果
// System.out.println(helloSpring);
}
}
执行结果:
先执行接口
Bean销毁时机