簡體   English   中英

使用類從外部模塊加載資源文件

[英]Loading resource file from external module using Class

我在嘗試從外部模塊的資源文件夾加載資源文件時遇到困難。 我正在使用 IntelliJ,我們的項目是使用 Maven 構建的。

使用模塊之前的原始代碼是這樣的:

getClass().getResourceAsStream(rulesFile)

這現在導致null結果。


模塊的結構如下:

client
    - java
        - org.example.client
            - Controller.java

data
    - java
        - ...
    - resources
        - org.example.data.files
            - rulesFile

在模塊client

getClass().getResourceAsStream(rulesFile)不起作用。

但是,如果我嘗試執行ModuleLayer.boot().findModule("data").get().getResourceAsStream(rulesFile) ,那么它工作正常。

我的問題是,是否可以使rulesFileclient模塊內的Controller.java可見,以便可以使用普通的類加載器? 我想避免必須明確指定它來自的模塊名稱,因為在其他地方使用了從data模塊加載文件的類似代碼。

我有哪些選項可以避免顯式給出模塊名稱?

我嘗試將以下內容添加到data模塊文件中,但沒有成功:

opens org.example.data.files to client

謝謝您的幫助!

http://maven.apache.org/pom.html#Resources

在您的客戶端模塊 pom.xml 中添加:

<project>
    ...

    <build>
    ...

        <resources>
            <resource>
                <directory>../data/src/main/resources/org/example/data/files</directory>
                <includes>
                    <include>rulesFile</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

模塊的結構如下:

client
    - java
        - org.example.client
            - Controller.java

data
    - java
        - Data.java
    - resources
        - org.example.data.files
            - rulesFile

就目前而言,也許不是最完美的解決方案,但似乎可以從加載data模塊從工作時, Class里面data模塊。

同樣重要的是要注意我也打開了client模塊的data資源文件夾。

而不是嘗試類似的東西:

Controller.class.getResourceAsStream(rulesFile)

如果你這樣做:

Data.class.getResourceAsStream(rulesFile)它有效,這是因為Data.java位於data模塊內,而rulesFile駐留在該模塊中。

在 Java .ear類型的包工件中,這也會發生在您需要一個模塊的類路徑以包含另一個模塊的地方。 在這種情況下,將必要的模塊標記為“想要”模塊中的依賴項應該將其合並到“想要”的類路徑中。 具體來說,這發生在需要訪問ejbs in a ear wars中。

您只需通過工件名稱將模塊添加到“想要”模塊的pom.xml的依賴項部分:

<dependencies>
  <dependency>
    <artifactId>data</artifactId>
  </dependency>
</dependencies

工件的其他屬性由您在 Maven 中的父 pom 推斷,因此您無需提及versiongroupId Scope 可以被引用為runtime但我認為這可能是默認值。

如果一切順利,您應該可以只執行getClass().getResourceAsStream(rulesFile)

暫無
暫無

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

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