In the IDE environment, you can directly use the exec-maven-plugin plug-in to run the java application, similar to the following:
1 <plugin> 2 <groupId>org.codehaus.mojo</groupId> 3 <artifactId>exec-maven-plugin</artifactId> 4 <version>1.2.1</version> 5 <executions> 6 <execution> 7 <goals> 8 <goal>exec</goal> 9 </goals> 10 </execution> 11 </executions> 12 <configuration> 13 <executable>java</executable> 14 <arguments> 15 <argument>-classpath</argument> 16 <classpath> 17 </classpath> 18 <argument>ctas.importer.reader.app.Program</argument> 19 </arguments> 20 </configuration> 21 </plugin>
Line 18, change to your own Main-Class class, and then use mvn exec:exec to run, but when deploying to the production environment, the server usually does not have a maven environment, and you can only use java -jar xxx.jar This way to run, here are some processing details:
First, the processing of dependencies
When the java application is running, it needs to find the dependent third-party jar. If the search for the classpath fails, an error will be reported. You can use it first.
mvn dependency:copy-dependencies -DoutputDirectory=target/lib
command to export all the dependent jar packages to the target/lib directory
2. Use maven-jar-plugin to modify the META-INF\MANIFEST.MF manifest file
In the final jar of the java application, after opening it with the decompression tool, you can see that there is an important manifest file MANIFEST.MF in the META-INF directory, where Main-Class and classpath can be specified. The structure is as follows:
1 Manifest-Version: 1.0 2 Built-By: jimmy 3 Build-Jdk: 1.7.0_09 4 Class-Path: lib/DataEntity-1.0.jar ... 5 Created-By: Apache Maven 3.2.3 6 Main-Class: ctas.importer.reader.app.Program 7 Archiver-Version: Plexus Archiver
其中第4行指定了classpath,也就是所依赖的jar包在什么地方,第6行表示main函数的入口类,默认情况下mvn clean package生成的jar包里,清单文件上并没有这2行,需要在pom.xml中添加插件
1 <plugin> 2 <groupId>org.apache.maven.plugins</groupId> 3 <artifactId>maven-jar-plugin</artifactId> 4 <configuration> 5 <archive> 6 <manifest> 7 <mainClass>ctas.importer.reader.app.Program</mainClass> 8 <addClasspath>true</addClasspath> 9 <classpathPrefix>lib/</classpathPrefix> 10 </manifest> 11 </archive> 12 <classesDirectory> 13 </classesDirectory> 14 </configuration> 15 </plugin>
Line 7 specifies Main-Class, and line 9 specifies the relative path of classpath, so after mvn package, the two items Main-Class and Class-Path will be automatically added to the manifest file
Ok, upload the jar package and lib directory to the server when deploying, and then test it. If it goes well, java -jar xxx.jar will do. If you want to run in the background, add nohup in front