Spring特定对象创建/销毁后,进行操作(接口实现)

本文详细介绍了在Spring框架中,如何通过实现InitializingBean和DisposableBean接口来定制对象的创建和销毁过程。通过具体示例展示了在UserService对象创建和销毁时执行自定义操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值