【1】通过Bean实现InitializingBean这个接口(定义初始化逻辑)
Invoked by a BeanFactory after it has set all bean properties supplied
由BeanFactoryBean提供的所有属性。
【2】通过DisposableBean这个接口(销毁bean)
由BeanFactory在单例销毁时调用。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ceshi.bean.Car;
/**
* bean的生命周期:
* bean的创建--->>初始化--->>销毁的过程
* 容器管理bean的生命周期
* 我们可以定义初始化和销毁的方法,容器在bean进行到当前生命周期的时候来调用我们自定义的
* 构造方法:
* 单实例:在容器启动的时候创建对象
* 多实例:在每次获取的时候创建对象
* 初始化
* 对象创建好,并赋值好,调用初始化方法....
* 销毁:
* 单实例:容器关闭的时候销毁
* 多实例:容器不会管理这个bean
*
*
* 初始化和销毁方法。
* 1)bean自定义初始化方法和销毁方法。
* <bean id="" class="" init-method="" destroy-method=""></bean>
* 2)通过Bean实现InitializingBean这个接口(定义初始化逻辑),
* Invoked by a BeanFactory after it has set all bean properties supplied
* 由BeanFactoryBean提供的所有属性。
* 通过DisposableBean这个接口(销毁bean)
* 由BeanFactory在单例销毁时调用。
*
*
*
*/
//配置类==配置文件(xml)
@Configuration //告诉Spring这个一个配制类
public class BeanConfigBeanOfLifeCycle {
@Bean(initMethod="init",destroyMethod="destroy",name="carMethodName")
public Car car(){
return new Car();
}
}
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() {
super();
// TODO Auto-generated constructor stub
System.out.println("Cat()");
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("destroy");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("afterPropertiesSet");
}
}