org.springframework.web.context.ContextLoaderListener java.lang.NoClassDefFoundError
1、Could not initialize class org.springframework.beans.factory.BeanCreationException
问题是: 定义了多个listener 都是通过实现public interface ServletContextListener extends EventListener 这个接口的,在tomcat 启动的时候报错
原因分析: 其中一个listener 【Listener1】中通过Spring的WebApplicationContextUtils 获取Spring中的ApplicationContext,再通过ApplicationContext获取Spring容器中的bean;通过debug(截图就不给了,有公司代码的信息) 发现:Listener1 先于ContextLoaderListener 的加载,导致Spring容器还没有实例化完成就获取ApplicationContext,此时获取ApplicationContext为null 因此报错。
ContextLoaderListener初始化ApplicationContext。
解决方式: 添加一个public class LocalContextLoaderListener extends ContextLoaderListener web.xml 中只配置LocalContextLoaderListener这个listener,因为只要在web.xml不配置listener ,ServletContextListener 也只是个普通的接口,这时候我们就可以通new 一个类再调用contextInitialized的方法实现方法实现的内容。通过这样的方法控制启动listener 的顺序。
具体的LocalContextLoaderListener实现:
public class LocalContextLoaderListener extends ContextLoaderListener {
@Override
public void contextInitialized(ServletContextEvent event) {
super.contextInitialized(event);
new Listener1().contextInitialized(event);
new Listener2().contextInitialized(event);
}
}
2、org.springframework.beans.FatalBeanException
问题是: spring 容器初始化mybatis 中的bean 的时候报出来的
问题分析: spring 在初始化mybatis 中的接口(dao)的时候,通过debug(截图就不给了,有公司代码的信息) 发现spring 找不到对应的实现类。后来发现是spring 在初始化mybatis 中的接口类先于sqlSessionFactory的加载导致的。
解决方法: 配置MapperScannerConfigurer 的时候 把sqlSessionFactory 通过配置sqlSessionFactoryBeanName 属性,依赖进去。
具体的xml 配置:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.xx.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>