一 指定初始化和销毁方法
通过@Bean指定init-method和destroy-method;
1 @Bean(initMethod="init",destroyMethod="detory") 2 public Car car(){ 3 return new Car(); 4 }
二 通过让Bean实现InitializingBean(定义初始化逻辑)
1 @Component 2 public class Cat implements InitializingBean,DisposableBean { 3 4 public Cat(){ 5 System.out.println("cat constructor..."); 6 } 7 8 @Override 9 public void destroy() throws Exception { 10 // TODO Auto-generated method stub 11 System.out.println("cat...destroy..."); 12 } 13 14 @Override 15 public void afterPropertiesSet() throws Exception { 16 // TODO Auto-generated method stub 17 System.out.println("cat...afterPropertiesSet..."); 18 } 19 20 }
三 可以使用JSR250
1 @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法 2 3 @PreDestroy:在容器销毁bean之前通知我们进行清理工作 4 5 @Component 6 public class Dog implements ApplicationContextAware { 7 8 //@Autowired 9 private ApplicationContext applicationContext; 10 11 public Dog(){ 12 System.out.println("dog constructor..."); 13 } 14 15 //对象创建并赋值之后调用 16 @PostConstruct 17 public void init(){ 18 System.out.println("Dog....@PostConstruct..."); 19 } 20 21 //容器移除对象之前 22 @PreDestroy 23 public void detory(){ 24 System.out.println("Dog....@PreDestroy..."); 25 } 26 27 @Override 28 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 29 // TODO Auto-generated method stub 30 this.applicationContext = applicationContext; 31 } 32 33 }
1 /** 2 * 后置处理器:初始化前后进行处理工作 3 * 将后置处理器加入到容器中 4 * 在bean初始化前后进行一些处理工作; 5 * postProcessBeforeInitialization:在初始化之前工作 6 * postProcessAfterInitialization:在初始化之后工作 7 */ 8 @Component 9 public class MyBeanPostProcessor implements BeanPostProcessor,Ordered { 10 11 @Override 12 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 13 // TODO Auto-generated method stub 14 System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean); 15 return bean; 16 } 17 18 @Override 19 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 20 // TODO Auto-generated method stub 21 System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean); 22 return bean; 23 } 24 25 @Override 26 public int getOrder() { 27 return 2; 28 } 29 30 }