Maven生成可以直接运行的jar包的多种方式:http://blog.csdn.net/xiao__gui/article/details/47341385#t2
(上面博文有介绍其他两种方法)
项目:Maven 3.3.9 + Spring 4.0.2 + Mybatis 3.2.6
主类:
package com.demo.boot;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.demo.service.UserService;
public class Boot {
public static void main(String[] args) throws InterruptedException{
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.setValidating(false);
context.load("classpath:spring-mybatis.xml");
context.refresh();
UserService userService = context.getBean(UserService.class);
while (true) {
System.out.println(userService.getUserById(1));
Thread.sleep(5000);
}
}
}
pom.xml中plugins加上maven-shade-plugin的:
其中 <mainClass>com.demo.boot.Boot</mainClass> 就是指定主类
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.demo.boot.Boot</mainClass>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<finalName>Demo</finalName>
</build>
然后到项目根目录,命令行执行:
mvn package
BUILD SUCCESS后,在项目的target目录下会有两个jar文件,original-xxx.jar跟xxx.jar。
运行其中的xxx.jar即可:
java -jar target/xxx.jar