Spring的几种初始化和销毁方法

一 指定初始化和销毁方法

通过@Bean指定init-method和destroy-method;

 @Bean(initMethod="init",destroyMethod="detory")
public Car car(){
return new Car();
}

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

 @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...");
}

}

三 可以使用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 {
// TODO Auto-generated method stub
this.applicationContext = applicationContext;
}

}

四 可以使用BeanPostProcessor

 /**
* 后置处理器:初始化前后进行处理工作
* 将后置处理器加入到容器中
* 在bean初始化前后进行一些处理工作;
* postProcessBeforeInitialization:在初始化之前工作
* postProcessAfterInitialization:在初始化之后工作
*/
@Component
public class MyBeanPostProcessor implements BeanPostProcessor,Ordered {

@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;
}

@Override
public int getOrder() {
return 2;
}

}
上一篇:PS图层混合算法之一(不透明度,正片叠底,颜色加深,颜色减淡)


下一篇:现代Web应用开发者必备的六大技能