簡體   English   中英

當以可執行jar運行時,Spring Boot項目找不到Hibernate.cfg.xml

[英]Spring Boot project can't find Hibernate.cfg.xml when run as executable jar

我看到在建立SessionFactory時找不到hibernate.cfg.xml的問題在某些情況下是很常見的,但是我的問題在這里有些具體。 即使在hibernate.cfg.xml中移動,我的項目在Eclipse中運行時也能正常工作。 我可以將其留在源代碼級別並執行以下操作:

        Configuration configuration = new Configuration();
        configuration = new Configuration();
        configuration.configure();

或者,我可以將其移動到其他位置並通過以下方式進行定義:

        Configuration configuration = new Configuration();
        configuration = new Configuration();
        configuration.configure("/path/to/hibernate.cfg.xml");

兩種方式都可以在Eclipse中使用。 但是,當我構建一個可執行jar來在其他地方運行該應用程序時,它在啟動時會抱怨:

Initial SessionFactory creation 
failed.org.hibernate.internal.util.config.ConfigurationException: Could not 
locate cfg.xml resource [hibernate.cfg.xml]
org.hibernate.internal.util.config.ConfigurationException: Could not locate 
cfg.xml resource [hibernate.cfg.xml]

我了解(或我認為是),原因是hibernate.cfg.xml並未包含在jar本身中,因此即使定義了路徑,也找不到它,但不確定如何要解決這個問題。 我認為,如果我可以將文件放入jar,那么它可能會起作用(也許classpath也需要為此輸入一個條目?),但實際上我不確定該怎么做。

它主要取決於您是否使用框架,如果是,則取決於您使用的框架。 如果您不使用任何框架,則可以在根路徑中保留hibernate.cfg.xml文件。 但是由於迫切需要使編碼過程標准化,因此框架通常希望該文件位於您的資源文件夾中,但是在這種情況下,您應該提供該配置文件的路徑而不是相對於根文件夾,而是完整路徑。

我認為您在這里使用絕對路徑:

configuration.configure("/path/to/hibernate.cfg.xml");

相反,您應該使用類路徑加載器。 像這樣的東西:

Resource r = new ClassPathResource("hibernate.cfg.xml")
String path = r.getURI().getPath();
configuration.configure(path);

包裝瓶子后應該可以使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM