普通Java工程使用的是Maven管理,如何将程序打包成JAR程序,直接运行呢?
- 配置文件独立于JAR程序
- 公共引用libs独立于JAR程序
以下配置文件最终结果:全部配置文件放在cfg目录下, 所有的引用类库放在libs目录下, 编译后的可执行JAR程序 imessage.jar 放在根目录下, 运行命令 java -jar imessage.jar
<build> <finalName>imessage</finalName> <sourceDirectory>src/main/java</sourceDirectory> <resources> <!-- 资源配置文件 --> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <targetPath>${project.build.directory}/cfg</targetPath> </resource> </resources> <plugins> <!-- 编译版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- 打包配置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <configuration> <archive> <manifest> <mainClass>com.dhcc.imessage.App</mainClass> <addClasspath>true</addClasspath> <classpathPrefix>libs/</classpathPrefix> </manifest> <!-- 配置文件外置 --> <manifestEntries> <Class-Path>cfg/</Class-Path> </manifestEntries> </archive> </configuration> </plugin> <!-- 拷贝依赖的jar包到libs目录 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.1.1</version> <executions> <execution> <id>copy</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory> ${project.build.directory}/libs </outputDirectory> </configuration> </execution> </executions> </plugin> <!-- 解决资源文件的编码问题 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.1.0</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- 打包source文件为jar文件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>3.0.1</version> <configuration> <attach>true</attach> <encoding>UTF-8</encoding> </configuration> <executions> <execution> <phase>compile</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
在使用IDE开发测试的时候,把这段注释掉<targetPath>${project.build.directory}/cfg</targetPath>
继续阅读
微信公众号
分享IT信息技术、北海生活的网站。提供北海本地化的信息技术服务。