一、@Bean指定初始化和销毁方法
- 在@Bean注解里指定
init-method
和destory-method
@Bean(initMethod = "init", destroyMethod = "destory")
二、InitializingBean和DisposableBean
- 让Bean实现
InitializingBean
(定义初始化逻辑)和DisposableBean
(定义销毁逻辑)接口package org.hao.bean; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; @Component public class Cat implements InitializingBean, DisposableBean { public Cat() { System.out.println("cat...constructor"); } public void destroy() throws Exception { System.out.println("cat destory..."); } public void afterPropertiesSet() throws Exception { System.out.println("cat afterPropertiesSet..."); } }
三、@PostConstruct和@PreDestroy
@PostConstruct
:在Bean创建完成并且属性赋值完成之后来执行初始化方法@PreDestroy
:在容器销毁Bean之前通知我们进行清理工作package org.hao.bean; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Component public class Dog { public Dog() { System.out.println("dog constructor..."); } //对象创建并赋值后调用 @PostConstruct public void init(){ System.out.println("Dog...PostConstruct"); } //容器移除对象之前调用 @PreDestroy public void destroy(){ System.out.println("Dog...PreDestory"); } }
四、BeanPostProcessor后置处理器
- 在Bean初始化前后进行处理
package org.hao.bean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Component; @Component public class MyBeanPostProcessor implements BeanPostProcessor { public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessAfterInitialization" + beanName + "=>" + bean); return bean; } public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessBeforeInitialization" + beanName + "=>" + bean); return bean; } }