Maven构建配置学习笔记
1. <build>标签核心配置
1.1 定制打包名称
xml
<finalName>${profiles.jarname}</finalName>
- 使用变量引用,配合profiles实现不同环境生成不同jar包名
- 避免手动修改,提高部署效率
1.2 Spring Boot插件配置
xml
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
includeSystemScope=true:将本地jar包(system scope依赖)也打包进最终jar,把systemPath
引用的本地 jar 也打进 BOOT-INF/lib,注意:只在 spring-boot-maven-plugin 2.1+ 有效;忘了加就 ClassNotFound。
- 解决第三方本地jar包在部署时缺失的问题
1.3 资源文件管理
xml
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>distribute/**</exclude>
</excludes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources/lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
</resource>
</resources>
- 排除特定目录 :
distribute目录下的环境配置文件不参与默认打包 - 本地jar包处理 :将
lib目录下的jar包复制到BOOT-INF/lib/ - 自定义资源:支持外部资源目录(如fonts)的打包
2. <profiles>多环境配置
2.1 环境定义结构
每个profile包含:
id:环境标识符properties:环境变量定义activation:激活条件build:环境特定的构建配置
2.2 本地开发环境
xml
<profile>
<id>local_dev</id>
<properties>
<profiles.jarname>local_dev-ms-service</profiles.jarname>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
- 默认激活环境
- 生成的jar包名包含
local_dev前缀
2.3 测试/生产环境
xml
<profile>
<id>server_test</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<goals><goal>run</goal></goals>
<configuration>
<tasks>
<copy todir="${basedir}/target/classes/">
<fileset dir="${basedir}/src/main/resources/distribute/server_test/" />
</copy>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
关键机制:
- 在
compile阶段执行Ant任务 - 将对应环境的配置文件复制到
target/classes/ - 实现环境配置的动态替换
3. 实际使用场景
3.1 打包命令
bash
# 本地开发(默认)
mvn clean package
# 测试环境
mvn clean package -P server_test
# 生产环境
mvn clean package -P server_prod
3.2 解决的问题
- 环境隔离:不同环境使用不同配置文件,避免配置混乱
- 包名区分:生成的jar包名包含环境标识,便于识别
- 本地依赖:解决第三方本地jar包的打包问题
- 资源管理:灵活控制哪些资源文件需要打包
4. 最佳实践建议
- 配置文件目录结构:
plain
resources/
├── distribute/
│ ├── server_test/
│ └── server_prod/
└── lib/
- profile命名规范 :使用
环境_用途格式,如server_test - 版本管理 :插件版本建议使用属性统一管理
这套配置很好地解决了多环境部署的常见问题,特别是配置文件管理和本地依赖打包这两个痛点。你在实际项目中使用时,可以根据具体需求调整资源路径和环境配置。