您的位置:首页 > 大数据 > 人工智能

Maven generates jar file with main class setting and dependency libs copy

2012-12-14 06:38 465 查看
When I write a pure java project, I'm afraid of writing deployment doc. Because I need to generate jar file. The most frustrating thing is add other libs into the jar. Maven is a fabulous tool which gives you different ways to deal with dependencies. In
our case, we keep external jars and our jar file separately. We just use maven's plugin, then all things will be done. Let me show you an example:

1. Config main class. In your pom.xml, add a <plugin> inside your <plugins>

<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>default-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.rujuan.MyMain</mainClass>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
<manifestEntries>
<mode>development</mode>
<url>${pom.url}</url>
</manifestEntries>
</archive>
</configuration>
</plugin>


2. Config dependencies. Use another plugin, very easy, right?

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</plugin>

If you don't specify outputDirectory, the default one is dependency.

Note: If you use Liferay IDE1.5, when you add maven-dependency-plugin it'll give you an error "maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e." . It doesn't matter, when you build
jar file, choose to use command line.

3. build .jar file

Go to your project folder where your pom.xml is located, run "mvn clean install". It'll generate lib folder within libs and project.jar inside target folder.

4. run jar file

java -jar project.jar

That's all. That's very easy, right? But I spent almost 1.5 hour on that, util my coworker tells me where to run the jar file. I made a mistake and go to maven repository to run the jar.


BTW, I ran into a problem in my project. I put my properties file inside src/main/java folder, maven ignore it when it builds jar for me. I tried to use <include>, but it excludes other xml files. The reason is I put the properties file in a wrong place.
I changed to put it under /scr/main/resources folder, maven automatically include it for me.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: