实现 *Aware 接口
*Aware 接口可以用于在初始化 bean 时获得 Spring 中的一些对象,如获取 Spring 上下文等。
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
public class SpringLifeCycleAware implements ApplicationContextAware {
private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleAware.class);
private ApplicationContext applicationContext ;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext ;
LOGGER.info("SpringLifeCycleAware start");
}
}
InstantiationAwareBeanPostProcessor
实现这个接口的类, 可以在类的实例化阶段, 做一些操作。这个接口有三个方法:
- Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName): 在实例化之前进行一些操作, 目的是提供一个机会由这个方法来实例化对象. 比如 proxy, mock
- boolean postProcessAfterInstantiation(Object bean, String beanName):bean set属性前执行, 如果返回false, 将会跳过属性处理. 这个一般都是返回true.
- PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName):属性构造完成, apply 到对象前执行, 传入 pvs 并返回 pvs, 有机会对 pvs 进行处理. 比如 required 检测在这一步.
InitializingBean, DisposableBean 接口
实现 InitializingBean,DisposableBean 这两个接口,也是在初始化以及销毁阶段调用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Service
public class SpringLifeCycleService implements InitializingBean,DisposableBean{
private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleService.class);
@Override
public void afterPropertiesSet() throws Exception {
LOGGER.info("SpringLifeCycleService start");
}
@Override
public void destroy() throws Exception {
LOGGER.info("SpringLifeCycleService destroy");
}
}
BeanPostProcessor
这个接口有两个方法:
- Object postProcessBeforeInitialization(Object bean, String beanName):在初始化之前 传入 bean 并返回 bean, 但返回的 bean 可以被包装或者替换
- Object postProcessAfterInitialization(Object bean, String beanName):同上, 也可以做一些 bean 初始化完成后的回调. 比如可以监听每一个 bean 的初始化时机.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Component
public class SpringLifeCycleProcessor implements BeanPostProcessor {
private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleProcessor.class);
/**
* 预初始化 初始化之前调用
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if ("annotationBean".equals(beanName)){
LOGGER.info("SpringLifeCycleProcessor start beanName={}",beanName);
}
return bean;
}
/**
* 后初始化 bean 初始化完成调用
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if ("annotationBean".equals(beanName)){
LOGGER.info("SpringLifeCycleProcessor end beanName={}",beanName);
}
return bean;
}
}