之前有个框架层面的需求是拦截所有的sql进行处理,因为工程里引用了mybatis,jdbc,hibernate,所以直接重写mysql驱动的EscapeProcessor类,这时候遇到了第一个问题,EscapeProcessor初始化在spring bean之前。
经过一番折腾,定义了一个spring boot启动时优先加载的配置,很快解决了第一个问题。
public class ClientBeanProcessor extends InstantiationAwareBeanPostProcessorAdapter implements BeanFactoryAware {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
throw new IllegalArgumentException(
"AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory);
}
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
// 通过主动调用beanFactory#getBean来显示实例化目标bean
SpringContextKit springContextKit = this.beanFactory.getBean(SpringContextKit.class);
System.out.println(springContextKit);
}
}
这时坑出现了,明明优先初始化的ApplicationContext是注入成功的,但是获取bean时一直为null,又经过了一番折腾,发现优先加载的bean和获取的bean不在一个类加载器内,ClientBeanProcessor 加载SpringContextKit到时用的是RestartClassLoader,获取bean使用时用的是AppClassLoader,去掉spring-boot-devtools,问题解决
网友评论