方法:通过让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并实现接口方法后,容器自动调用初始化和销毁的方法。