[英]using same resource location executing and building a maven2 java jar project
我在使用maven2和Java jar項目時遇到了一些問題。
這是我的項目文件系統:
MyApp
-- /src/main/java
-- my.package
-- Main.java
-- /src/main/resources
-- application.properties
Pom.xml使用標准的maven插件配置為具有自定義的打包階段:
<!-- copy resources from /src/main/resource to target -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4</version>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>resources</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- create an executable jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<finalName>${project.artifactId}-${project.version}</finalName>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>my.package.Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- copy dependencies jars to target/lib folder -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
使用此配置並調用mvn包,一切正常:在目標文件夾中創建一個新的jar,並復制資源和依賴項。 通過新File(“ application.properties”)引用文件application.properties,JRE可以找到它。 如果我從目標文件夾手動運行jar,它將起作用!
現在我的問題是:我想添加exec-maven-plugin以在eclipse中直接執行我的項目。 這是我在pom.xml中的新插件:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<executable>java</executable>
<mainClass>my.package.Main</mainClass>
</configuration>
</plugin>
通過這種方式,我的類得以執行並且所有的依賴關系都得到了滿足,但是卻找不到我的資源(特別是application.properties),因為我的程序工作目錄是由MyApp / target插入的MyApp。 使用配置是沒有用的。
我該如何解決這個問題? 提前致謝
好吧,我想到兩件事。
a)不要通過maven exec運行,而只是通過Eclipse作為獨立應用程序運行(即運行主類)。 您應該對Eclipse項目進行預處理,以便設置正確的類路徑。
b)不要使用常規的文件系統訪問,而是將要加載的文件放在類路徑上,並使用getClass()。getClassLoader()。getResourceAsStream()進行加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.