在Spring容器中,实例对象都会有三个过程,创建,初始化和消亡。
创建 Bean 的方式
@Bean 注解指定方法
1 2 3 4
| @Bean(initMethod = "init",destroyMethod = "destroy") public Dog getDog(){ return new Dog(); }
|
InitializingBean和DisposableBean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Cat implements InitializingBean, DisposableBean { public Cat(){ RzLogger.info("cat create"); } @Override public void destroy() throws Exception { RzLogger.info("cat destroy"); }
@Override public void afterPropertiesSet() throws Exception { RzLogger.info("cat afterPropertiesSet"); } }
|
@PostConstruct和 @PreDestroy
@PostConstruct
:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy
:在容器销毁bean之前通知我们进行清理工作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Dog { public Dog() { RzLogger.info("创建Dog"); } @PostConstruct public void init() { RzLogger.info("Dog init PostConstruct"); }
@PreDestroy public void destroy() { RzLogger.info("Dog destory PreDestroy"); } }
|
BeanPostProcessor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class RzBeanPostProcessor implements BeanPostProcessor {
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { RzLogger.info("Before init "+beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { RzLogger.info("After init "+beanName); return bean; } }
|