maven指定运行main函数

415 阅读1分钟

背景

最近自己写的小项目,打包的时候会出现问题,总是提示缺少主类或者打包好后报classNotFoundException错误,最后才发现在这个问题

<build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    ....
                </plugin>
            </plugins>
    </pluginManagement>
</build>

搜索了一下stackoverflow The difference between <pluginManagement/> and <plugins/> is that a <plugin/> under:

  • <pluginManagement/> defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.
  • <plugins/> is an actual invocation of the plugin. It may or may not be inherited from a <pluginManagement/>.

You don't need to have a <pluginManagement/> in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like: 大概的意思是pluginManagement是为了有父pom方便继承 而plugin是真实调用的

所以,我们要确定一点是,我们需要修改的是build标签下的plugins而不是build pluginManagement下的plugins

方法一:修改jar-plugin,里面加入参数

修改compiler-plugin
 <plugin>
   <artifactId>maven-compiler-plugin</artifactId>
   <configuration>
     <source>1.8</source>
     <target>1.8</target>
     <encoding>UTF-8</encoding>
     <showDeprecation>true</showDeprecation>
   </configuration>
   <version>3.8.0</version>
</plugin>
修改jar-plugin
<plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>com.huskyui.LogMain</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>

方法二:加入shade插件

官方文档

<plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>${app.main.class}</Main-Class>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>