How to access a XML file in a maven project so it stays available when packaged

雨燕双飞 提交于 2020-01-01 10:53:31

问题


I currently started working on a maven web-app project that needs to be launched with the jetty:run-exploded goal for development/debugging in eclipse.

Now, I have an XML file which contents I need to access at runtime. My problem is: where to put the file so that the code that does the reading works both in "exploded" and packaged (i.e. in the WAR) mode?

Putting the file in src/main/java (so as to be in the classpath) won't cut it since maven filters out all non-java files on packaging. When the file is in src/main/resources, one mean would be to figure out the root path of the project (during eclipse development) and look into that directory - but this won't be the case anymore when the project will be packaged.

Of course I could go into writing code that tries to read the file from both locations, but this seems rather cumbersome. Any suggestions?


回答1:


Files in src/main/resources are copied to the target/classes directory and are available on the class path. Just read them from the class path. As explained in How do I add resources to my JAR? from the maven documentation (with a test resource here):

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...



回答2:


In such case I put the file under src/main/resources directory and use Spring's ClassPathResource. This way the file is accessible in IDE, during Maven build process and in runtime.



来源:https://stackoverflow.com/questions/2643091/how-to-access-a-xml-file-in-a-maven-project-so-it-stays-available-when-packaged

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!