Spring特定对象创建/销毁后,进行操作(XML配置文件实现)
步骤
- 在类中创建对应方法
- 在bean标签中添加
init-method
destory
属性,并添加对应值(方法名)
相关属性
属性名 | 属性值 | 功能 |
---|---|---|
init-method | 方法名 | 在对象创建后执行 |
destory | 方法名 | 在对象销毁后执行 |
实例
在UserService 类中创建对应方法并注解
public class UserService {
public void start(){
System.out.println("我被创建了...");
}
public void destory(){
System.out.println("我被销毁了...");
}
}
在XML配置文件中进行相关配置(开启对应注解解析)
<bean class="com.bb.service.UserService" id="userService" init-method="start" destroy-method="destory"/>
测试方法
@Test
public void test2(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us = (UserService) ac.getBean("userService");
ac.registerShutdownHook();
}
打印输出
我被创建了...
我被销毁了...
总结:实现 InitializingBean
DisposableBean
接口也可以实现本操作。