关于maven的一些记录

普通maven包含依赖打包成jar

使用shade插件,可以将依赖包含在jar中,指定入口类即可使用java -jar命令启动。
查看更多 shade 用法

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.1</version>
            <executions>
                <execution>
                    <!--将插件绑定到maven的package生命周期上-->
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <!--自动将项目中没有使用的类排除-->
                        <minimizeJar>true</minimizeJar>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <!--入口启动类全限定名-->
                                <mainClass>com.example.App</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

普通maven项目中的资源管理

普通maven项目编译时只包含class文件,其他文件都会排除,如项目中的xxx.properties文件,
xxx.xml文件等。项目的pom.xml文件加入以下配置,编译时可包含资源文件。

<build>
    <resources>
        <resource>
            <!-- 设定主资源目录  -->
            <directory>src/main/resources</directory>
            <includes>
                <!--resources目录下的所有文件和目录-->
                <include>**</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

项目资源文件一般放在 src/main/resources 目录下,打包时resources里的文件和目录会直接到
jar文件中,通过解压软件可以看到。调用时可使用以下代码获取配置文件或者文件流

public class Test {
    public static void main(String[] args) {
        Properties config = new Properties();
        try(InputStream is = Test.class.getResourceAsStream("/xxx.properties")) {
            config.load(new InputStreamReader(is,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(config.getProperty("key"));
    }
}
不积跬步无以至千里
原文地址:https://www.cnblogs.com/xiaogblog/p/15424394.html