繁体   English   中英

使用相同的资源位置执行和构建maven2 java jar项目

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM