您的位置:首页 > 编程语言 > Java开发

Spring注解驱动开发-Bean的生命周期

2019-03-21 12:45 519 查看

bean的生命周期:bean创建—初始化----销毁的过程
容器管理bean的生命周期:我们可以自定义初始化和销毁方法;容器在bean进行到当>前生命周期的时候来调用我们自定义的初始化和销毁方法

一、指定初始化和销毁方法

通过@Bean指定init-method和destroy-method;
如果是Bean是多例的,spring只负责创建Bean,在容器关闭的时候并不会销毁bean
public class Car {

public Car(){
System.out.println("Car Constructor ......");
}

public void init(){
System.out.println("Car initial ......");
}

public void destroy(){
System.out.println("Car destroy ......");
}
}
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car(){
return new Car();
}
@Test
public  void test01(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifeCyleConfig.class);
System.out.println("IOC容器创建完成");
Car car = applicationContext.getBean(Car.class);
((AnnotationConfigApplicationContext) applicationContext).close();

}

二、通过让Bean实现InitializingBean(定义初始化逻辑) DisposableBean(定义销毁逻辑

public class Student implements InitializingBean ,DisposableBean {
public Student() {
System.out.println("Student Constructor ......");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Student initial ........");
}
@Override
public void destroy() throws Exception {
System.out.println("Student destroy ...........");
}
}

三、可以使用JSR250;

@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作
@Component
public class Dog implements ApplicationContextAware {
//@Autowired
private ApplicationContext applicationContext;
public Dog(){
System.out.println("dog constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init(){
System.out.println("Dog....@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void detory(){
System.out.println("Dog....@PreDestroy...");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

四 、BeanPostProcessor【interface】:bean的后置处理器;

在bean初始化前后进行一些处理工作;
postProcessBeforeInitialization:在初始化之前工作
postProcessAfterInitialization:在初始化之后工作
public class MyBeanPostProcessor implements BeanPostProcessor {

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
return bean;
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: