Spring中Bean的生命周期之-----InitializingBean,DisposableBean

方法:通过让Bean实现InitializingBean(定义初始化逻辑), DisposableBean(定义销毁逻辑)

注:单例模式下容器会自动销毁bean,但原型模式下不会销毁,也就是不会调用销毁方法。


1、创建一个Bean类

承接口InitializingBean,DisposableBean,实现初始化方法afterPropertiesSet()和销毁方法destroy()

并用@Component标注,可以进行动态扫描

package com.atguigu.bean;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class Cat implements InitializingBean,DisposableBean {
	
	public Cat(){
		System.out.println("cat constructor...");
	}

	@Override
	public void destroy() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("cat...destroy...");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("cat...afterPropertiesSet...");
	}

}

二、配置类

 标注@ComponentScan("com.atguigu.bean"),表示扫描该包下所有有@Controller,@Service,@Repository,@Component注解的类

@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
	
	//@Scope("prototype")
	@Bean(initMethod="init",destroyMethod="detory")
	public Car car(){
		return new Car();
	}

}

三、测试

 

说明:承接口InitializingBean,DisposableBean并实现接口方法后,容器自动调用初始化和销毁的方法。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值