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

时间:2014-09-06 14:30:17

标签: 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";
  }
}

问题始终存在,无论我是直接创建对象还是使用@Autowired。在这里的代码中,我展示了@Autowired的情况,但这并不重要 - 我可以写private WireTest wt = new WireTest(),异常也是一样。

WireTest.java上课:

@Service
public class WireTest {
  public String getString() {return (DBhelper.getString());}
}

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

public class DBhelper {
    public static String getString() {return "Hi!";}
}

例外:

HTTP Status 500 - Handler processing failed; nested exception is         
java.lang.NoClassDefFoundError: Could not initialize class org.sher.wtpractice.dao.DBhelper

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

My 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>

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>

我使用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!";}
}

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:5)

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

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

private static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        sessionFactory = createSessionFactory();
    }
    return sessionFactory;
}

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

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

try {
    ...
} catch (Throwable e) {
    e.printStackTrace();
    throw new RuntimeException(e);
}

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

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

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

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

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

答案 1 :(得分:0)

检查DBhelper的静态初始化。

"NoClassDefFoundError: Could not initialize class" error

在这种情况下,将sessionFactory实例化为spring bean,然后让spring容器将它组装到DBhelper