在springboot中整合shiro的时候,在配置项中往往需要配置LifecycleBeanPostProcessor,他是用来管理shiro一些bean的生命周期
/** * 管理Shiro中一些bean的生命周期 */
@Bean("lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/** * 扫描上下文,寻找所有的Advistor(通知器) * 将这些Advisor应用到所有符合切入点的Bean中。 */
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
return proxyCreator;
}
LifecycleBeanPostProcessor.java
public class LifecycleBeanPostProcessor implements DestructionAwareBeanPostProcessor, PriorityOrdered {
.........................
//省略。。。
public Object postProcessBeforeInitialization(Object object, String name) throws BeansException {
if (object instanceof Initializable) {
((Initializable) object).init();
}
return object;
}
public Object postProcessAfterInitialization(Object object, String name) throws BeansException {
// Does nothing after initialization
return object;
}
public void postProcessBeforeDestruction(Object object, String name) throws BeansException {
if (object instanceof Destroyable) {
((Destroyable) object).destroy();
}
}
}
这里可以发现LifecycleBeanPostProcessor这个类实现了DestructionAwareBeanPostProcessor,
DestructionAwareBeanPostProcessor.java
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
void postProcessBeforeDestruction(Object var1, String var2) throws BeansException;
default boolean requiresDestruction(Object bean) {
return true;
}
}
这里可以发现DestructionAwareBeanPostProcessor这个类实现了BeanPostProcessor
BeanPostProcessor.java
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
再看看spring在初始化bean的时候:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
//省略。。。
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
//省略。。。
invokeInitMethods(beanName, wrappedBean, mbd);
//省略。。。
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
其中applyBeanPostProcessorsBeforeInitialization和applyBeanPostProcessorsAfterInitialization就对应执行的是LifecycleBeanPostProcessor的postProcessBeforeInitialization和postProcessAfterInitialization,这里只举初始化的例子,销毁bean同理可得。
所有,可以知道LifecycleBeanPostProcessor将Initializable和Destroyable的实现类统一在其内部自动分别调用了Initializable.init()和Destroyable.destroy()方法,从而达到管理shiro bean生命周期的目的。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_43296313/article/details/120825844
内容来源于网络,如有侵权,请联系作者删除!