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.
本文介绍如何利用Maven工具简化Java项目的部署过程,包括配置主类、依赖管理和构建jar文件。通过实例演示了如何设置Maven插件来自动化生成jar文件,并配置依赖,避免手动添加外部jar包的问题。最后,还提到了遇到的问题及解决方案。
4052

被折叠的 条评论
为什么被折叠?



