Spring特定对象创建/销毁后,进行操作(接口实现)
Spring对象的创建以及销毁有许多的步骤。在这些步骤之间,我们可以进行相应的操作。
在该对象上实现 InitializingBean
DisposableBean
接口即可。
接口名 | 功能 |
---|---|
InitializingBean | 当该对象被创建时执行方法内代码 |
DisposableBean | 当该对象被销毁时执行方法内代码 |
举例
在UserService 对象创建/销毁时打印一句话
public class UserService implements InitializingBean,DisposableBean{
public UserService(){
System.out.println("--UserService构造方法执行--");
}
@Override
public void destroy() throws Exception {
System.out.println("---销毁----");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("初始化之后");
}
}
测试
@Test
public void test2(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us = (UserService) ac.getBean("userService");
ac.registerShutdownHook();
}
输出
--UserService构造方法执行--
初始化之后
---销毁----
依赖jar包
com.springsource.org.apache.commons.logging-1.1.1.jar
spring-aop-4.3.10.RELEASE.jar
spring-aspects-4.3.10.RELEASE.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar