2014-09-06 225 views
3

我正在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

回答

4

嘗試延遲加載會話工廠,而不是通過分配給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

0

檢查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

相關問題