Bean的生命周期指的是组件在容器中实例化到初始化到销毁的整个过程;
- 实例化: 单实例: 在容器启动时实例化对象; 多实例: 在每次获取的时候实例化对象
- 初始化: 对象实例化完成, 并赋值好, 调用初始化方法;
- 销毁: 单实例: 在容器关闭时调用销毁方法销毁bean;多实例: 容器不会管理这个bean的销毁方法, 所以需要手动调用bean的销毁方法;
生命周期管理方法:
- 通过
@Bean
的属性initMethod
指定初始化方法;通过@Bean
的属性destroyMethod
指定销毁方法
@Configuration
public class SpringConfig {
// 指定的初始化和销毁方法
@Bean(initMethod = "init", destroyMethod = "destory")
public User user() {
System.err.println("@bean..user..");
return new User();
}
}
// 在需要注册的bean中定义初始化和销毁的方法
public class User {
public User() {
System.err.println("user...contrutor...");
}
public void init() {
System.err.println("user...init...");
}
public void destory() {
System.err.println("user...destory...");
}
}
- 将
bean
实现InitializingBean
接口重写afterPropertiesSet()
方法定义初始化; 将bean实现DisposableBean
接口重写destory()
方法定义销毁方法;
@Configuration
@ComponentScan(value = "study.bryan.spring") // 使用包扫描将userService注册至容器中
public class SpringConfig {
}
// 实现InitializingBean和DisposableBean接口, 重写afterPropertiesSet和destroy
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
@Service("userService")
public class UserServiceImpl implements InitializingBean, DisposableBean{
public void afterPropertiesSet() throws Exception {
System.err.println("userService... init");
}
public void destroy() throws Exception {
System.err.println("userService... destory");
}
}
- 使用JSR250:
@PostConstruct
注解: 在bean创建完成并且属性赋值完成后, 执行初始化方法;@PreDestory
: 在容器销毁bean之前调用被此注解标注的方法;
@Configuration
@ComponentScan(value = "study.bryan.spring") // 使用包扫描将userService注册至容器中
public class SpringConfig {
}
@Service("userService")
public class UserServiceImpl {
@PostConstruct
public void init() {
System.err.println("userService... init");
}
@PreDestory
public void destroy() {
System.err.println("userService... destory");
}
}
- 实现
org.springframework.beans.factory.config.BeanPostProcessor
(bean后置处理器)接口, 重写postProcessBeforeInitialization()
和postProcessAfterInitialization()
方法;在各个组件初始化前,spring
调用postProcessBeforeInitialization()
方法, 在组件初始化完成后,spring
调用postProcessAfterInitialization()
方法;
因此 bean的生命周期变为 实例化–>BeanPostProcessor.postProcessBeforeInitialization()
–>初始化–>BeanPostProcessor.postProcessAfterInitialization()
–>销毁;
@Component// 将后置处理器注册为组件, spring才会调用此类的两个方法
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.err.println("postProcessBeforeInitialization..."+beanName);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.err.println("postProcessAfterInitialization..."+beanName);
return bean;
}
}