Spring:java.lang.NoClassDefFoundError:无法初始化类

ars*_*ars 4 java spring hibernate spring-mvc

我正在Spring MVC中开发一个小的Web应用程序.每次我尝试在任何控制器中获取自定义类时,我都会得到异常,以防该类使用另一个自定义类.在示例中更容易显示:

控制器,我正在尝试获取自定义类WireTest的对象:

@Controller
@RequestMapping("/offices")
public class OfficesController {

  @Autowired
  private WireTest wt;

  @RequestMapping("")
  public String offices(Model model) {
    model.addAttribute("test", wt.getString());
    return "offices";
  }
}
Run Code Online (Sandbox Code Playgroud)

无论我是直接创建对象还是使用@Autowired,问题总会发生.在这里的代码中,我展示了@Autowired的情况,但这没关系 - 我可以写private WireTest wt = new WireTest(),并且异常将是相同的.

WireTest.java 类:

@Service
public class WireTest {
  public String getString() {return (DBhelper.getString());}
}
Run Code Online (Sandbox Code Playgroud)

部分DBhelper.java类(也有其他静态成员,完整代码如下):

public class DBhelper {
    public static String getString() {return "Hi!";}
}
Run Code Online (Sandbox Code Playgroud)

例外情况:

HTTP Status 500 - Handler processing failed; nested exception is         
java.lang.NoClassDefFoundError: Could not initialize class org.sher.wtpractice.dao.DBhelper
Run Code Online (Sandbox Code Playgroud)

我也可以在控制台应用程序中使用这些类而没有任何问题,因此它可以在Spring之外运行.

我的Spring配置:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>
Run Code Online (Sandbox Code Playgroud)

dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:component-scan base-package="org.sher.wtpractice.spring, org.sher.wtpractice.dao" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

我正在使用Maven进行构建,将Tomcat 7用作服务器,如果这很重要的话.Spring版本是4.0.1.RELEASE

更新:DBhelper.java的完整代码

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import java.util.Calendar;
import java.util.Date;
public class DBhelper {
    private static final SessionFactory sessionFactory = createSessionFactory();

    private static SessionFactory createSessionFactory() {
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        return configuration.buildSessionFactory(serviceRegistry);
    }

    public static Object queryWrapper(DBoperation op) {
        Session session = sessionFactory.openSession();
        Transaction transaction = null;
        Object result = null;
        try {
            transaction = session.beginTransaction();
            result = op.operation(session);
            session.getTransaction().commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
//            throw e;
        } finally {
            if (session != null && session.isOpen())
                session.close();
        }
        return result;
    }
    public static Date normalizeCal(Calendar cal) {
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
    public static String getString() {return "Hi!";}
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Luk*_*ard 6

尝试延迟加载会话工厂,而不是通过分配final字段来静态初始化它.

例如,创建一个如下所示的方法,该方法返回会话工厂,并在必要时创建它.每当您想使用会话工厂时,请调用此方法而不是直接引用该字段:

private static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        sessionFactory = createSessionFactory();
    }
    return sessionFactory;
}
Run Code Online (Sandbox Code Playgroud)

就个人而言,我不喜欢任何非平凡的静态初始化,因为你无法控制它何时发生.使用上述方法,您可以控制:会话工厂在您第一次使用它时创建.

如果你想知道问题是什么,我有两个建议.首先,重新启动Web应用程序容器,看看是否第一次收到不同的异常消息.('第一次'在这里很重要:Could not initialize class意味着JVM已经尝试过并且无法初始化类.)其次,尝试将createSessionFactory方法的内容包装 在try- catch块中,如下所示:

try {
    ...
} catch (Throwable e) {
    e.printStackTrace();
    throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)

但是,我不能保证这两种方法都能为你提供很多启示.

编辑:而不是仅仅推测,我决定尝试这一点,看看会发生什么.所以我使用Spring和Hibernate敲了一个小的Web应用程序并将它部署到Tomcat.在尝试使其工作时,我在尝试读取Hibernate配置时遇到了一些问题,这是由于我犯了以下错误:

  • 我没有在.war文件中包含hibernate.cfg.xml文件,
  • 我没有在.war文件中包含数据库的JDBC驱动程序JAR,
  • 我试图连接的数据库已关闭.

在每种情况下我的第一种方法都有效 Tomcat重新启动后发出的第一个请求给了我一个ExceptionInInitializerError更详细的信息.第二次和随后的请求给了我NoClassDefFoundError一些没有告诉我很多关于这个问题的信息.

问题是,一旦ExceptionInInitializerError为类抛出一个,JVM会将此类列入黑名单,并且随后将拒绝对其执行任何操作.所以你只有一次机会看到静态初始化代码出了什么问题.如果您按照我上面的建议懒洋洋地初始化Hibernate,那么每次都会得到详细的异常消息.考虑避免静态初始化的另一个原因.