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

问题描述:

我正在Spring MVC中开发一个小型的Web应用程序。每次我尝试在任何控制器中获取自定义类时,我都会遇到异常,以防该类使用另一个自定义类。这是比较容易显示在例如:Spring:java.lang.NoClassDefFoundError:无法初始化类

控制器,在那里我试图让自定义类的对象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之外工作。

我的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的服务器,如果该事项。 春季版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!";} 
} 

的完整代码任何帮助将不胜感激!

+0

DBhelper类是否是任何jar文件的一部分? – zerocool 2014-09-06 14:44:02

+0

不。从这个角度来看,DBhelper和WireTest类的唯一区别在于它们位于不同的包中 - WireTest更深一层。 – ars 2014-09-06 14:47:09

+0

你能否解开战争文件并检查这个类是否被maven打包成战争的一部分? – zerocool 2014-09-06 14:52:05

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

例如,创建一个如下所示的方法,该方法返回会话工厂,并在必要时创建它。每当你要使用的会话工厂,调用此方法来代替直接引用领域:

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

我个人不喜欢静态初始化任何东西不平凡的,因为你在外面当它发生的控制权。通过上述方法,您可以控制:会话工厂在第一次需要使用时创建。

如果你想知道问题是什么,我有两个建议。首先,重新启动您的Web应用程序容器,看看您是否第一次得到不同的异常消息。 (“第一时间”在这里很重要:Could not initialize class意味着JVM已经尝试和失败,初始化类。)其次,尽量包裹createSessionFactory方法的内容在try - catch块,如以下几点:

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

但是,我不能保证任何一种方法都能为您提供很多启发。

编辑:我决定尝试一下,看看会发生什么。所以我使用Spring和Hibernate打开了一个小型Web应用程序,并将其部署到Tomcat。

  • 我没有包含在.war文件hibernate.cfg.xml文件:在试图获得它的工作我试图读取Hibernate的配置,引起了我做出如下的错误时遇到的几个问题,
  • 我没有在.war文件中包含数据库的JDBC驱动程序JAR,
  • 我试图连接的数据库已关闭。

在每种情况下,我的第一种方法奏效。在Tomcat重启后发出的第一个请求给了我一个ExceptionInInitializerError以及下面的更多细节。第二次和随后的要求给了我NoClassDefFoundError,这并没有告诉我有关这个问题的很多信息。

问题是,一旦对一个类抛出了ExceptionInInitializerError,JVM会将这个类列入黑名单,并将拒绝对它进行任何处理。所以你只有一次机会看到静态初始化代码出了什么问题。如果您按照上面的建议懒惰地初始化Hibernate,那么您每次都会收到详细的异常消息。考虑这个避免静态初始化的另一个原因。

+0

在过去的几个小时里,我用Spring方式重写了所有的Hibernate代码 - 在web.xml中声明了bean,自动装配和数据库连接(老实说,我仍然不明白为什么Spring开发人员会这样做)。它没有帮助,但错误是不同的 - Tomcat无法启动应用程序。所以我查看了日志并最终了解到Tomcat无法找到JDBC驱动程序。经过一番搜索后,我发现Tomcat在它自己的lib文件夹中搜索JDBC驱动程序,而不是WAR,并且问题解决了。 – ars 2014-09-06 22:01:39

+0

感谢您的建议。我认为,如果我的'createSessionFactory'是以懒惰的方式编写的,那么这个异常就足以说明问题的原因了,所以这个问题会立即得到解决。所以我将你的答案标记为已接受。 – ars 2014-09-06 22:01:59

检查DBhelper的静态初始化。

"NoClassDefFoundError: Could not initialize class" error

在此情况下,实例sessionFactory弹簧豆,并让弹簧容器它装配到DBhelper

+0

嗯,我很新春天,并不太明白如何做到这一点。我应该使用静态最终的SessionFactory对象创建单独的类,将其标记为Bean(@Service,我想)并将其自动装入DBhelper?此外,我不明白为什么我应该更改与Spring功能相关的与Hibernate相关的代码。有没有更优雅的方式?人们通常如何处理这个问题 – ars 2014-09-06 17:07:55

+0

你的春季 - 冬眠问题的链接是非常有用的,我会尽力做到这一点。但我仍然没有得到问题的核心。为什么Spring不能做简单的控制台应用程序? – ars 2014-09-06 17:24:48

+0

因为hibernate和这些东西总是需要配置,并且Spring IoC从业务代码中提取配置。你可以阅读一些文件。 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html – Loki 2014-09-06 17:37:53