1.什么是bean?
Spring Bean是被实例的,组装的及被Spring 容器管理的Java对象。
Spring 容器会自动完成@bean对象的实例化。
创建应用对象之间的协作关系的行为称为:装配(wiring),这就是依赖注入的本质。
2.Bean生命周期几种方式:
2.1通过@Bean注解指定初始化和销毁方法
@Bean(initMethod = "init",destroyMethod = "destroy")
@Configuration public class MyLifeCycleConfig { @Scope("prototype") @Bean(initMethod = "init",destroyMethod = "destroy") public Dog dog(){ return new Dog(); } }
applicationContext.close();关闭容器
单实例: 调用close()关闭容器,则会调用销毁方法
多实例: 调用close()关闭容器,则不会调用销毁方法
构造(对象创建)
单实例:在容器启动的时候创建对象
多实例:在每次获取的时候创建对象
初始化:
对象创建完成,并赋值好,调用初始化方法。。。
销毁:
单实例:容器关闭的时候销毁
多实例:容器不会管理这个bean;容器不会调用销毁方法;
2.2 实现初始化接口InitializingBean 和 销毁接口DisposableBean
通过让Bean实现InitializingBean(定义初始化逻辑); DisposableBean(定义销毁逻辑);
@Component public class Cat implements InitializingBean, DisposableBean { public Cat(){ System.out.println("cat...构造器..."); } public void destroy() throws Exception { System.out.println("cat ....destroy...."); } public void afterPropertiesSet() throws Exception { System.out.println("cat ...afterPropertiesSet...."); } }
2.3 使用JSR250 java中的注解
- @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
- @PreDestroy:在容器销毁bean之前通知我们进行清理工作
@Component public class Tiger { public Tiger(){ System.out.println("tiger...constructor...."); } @PostConstruct public void init(){ System.out.println("tiger....@postConstruct..."); } @PreDestroy public void destroy(){ System.out.println("tiger....@PreDestroy....."); } }
2.4 使用接口 BeanPostProcessor :bean的后置处理器;
接口BeanPostProcessor是 在bean初始化前后进行一些处理工作;
- postProcessBeforeInitialization:在初始化之前工作
- postProcessAfterInitialization:在初始化之后工作
@Component public class MyBeanPostProcessor implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean); return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean); return bean; } }
3.小结
1)、指定初始化和销毁方法;
通过@Bean指定init-method和destroy-method;
2)、通过让Bean实现InitializingBean(定义初始化逻辑),
DisposableBean(定义销毁逻辑);
3)、可以使用JSR250;
@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作
4)、BeanPostProcessor【interface】:bean的后置处理器;
在bean初始化前后进行一些处理工作;
postProcessBeforeInitialization:在初始化之前工作
postProcessAfterInitialization:在初始化之后工作