maven常用的插件
补充几个maven常用的插件。
1. git-commit-id-plugin
官网:https://github.com/git-commit-id/git-commit-id-maven-plugin
这个插件在分布式部署环境非常有用,可以通过此插件看出打包所处的git环境,分支、仓库、提交的head信息等。
包含两个目标:
1.git-commit-id:revision:将构建时的信息保存到指定文件中或maven的属性中。
2.git-commit-id:validateRevision:校验属性是否符合预期值,默认绑定阶段:verify。(这个不常用)
1. 增加git.properties信息和增加Controller查看信息
1.pom引入
<!-- git-commit-id-plugin --> <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> <executions> <execution> <goals> <goal>revision</goal> </goals> </execution> </executions> <configuration> <!--构建过程中,是否打印详细信息--> <verbose>true</verbose> <!--日期格式--> <dateFormat>yyyyMMddHHmmss</dateFormat> <!--是否生成"git.properties"文件;默认值:false;--> <generateGitPropertiesFile>true</generateGitPropertiesFile> <!--指定"git.properties"文件的存放路径--> <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties </generateGitPropertiesFilename> </configuration> </plugin>
2.执行revision 目标
liqiang@root MINGW64 /e/xiangmu/springboot-ssm (master) $ mvn git-commit-id:revision [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building springboot-ssm 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- git-commit-id-plugin:3.0.1:revision (default-cli) @ springboot-ssm --- [INFO] dotGitDirectory E:\xiangmu\springboot-ssm\.git [INFO] Collected git.build.user.name with value qiaozhi [INFO] Collected git.build.user.email with value qiao_liqiang@163.com [INFO] Collected git.branch with value master [INFO] --always = true [INFO] --dirty = -dirty [INFO] --abbrev = 7 [INFO] Tag refs [[]] [INFO] Created map: [{}] [INFO] evalCommit is [9120cf8905b7a6a44fbfe755c511b0602efc16e7] [INFO] Collected git.commit.id.describe with value 9120cf8-dirty [INFO] Collected git.commit.id.describe-short with value 9120cf8-dirty [INFO] Collected git.commit.id with value 9120cf8905b7a6a44fbfe755c511b0602efc16e7 [INFO] Collected git.commit.id.abbrev with value 9120cf8 [INFO] Collected git.dirty with value true [INFO] Collected git.commit.user.name with value qqiaoliqiang [INFO] Collected git.commit.user.email with value 954318308@qq.com [INFO] Collected git.commit.message.full with value ▒▒▒▒git▒▒Ϣ▒鿴▒▒▒ [INFO] Collected git.commit.message.short with value ▒▒▒▒git▒▒Ϣ▒鿴▒▒▒ [INFO] Collected git.commit.time with value 20201113140739 [INFO] Collected git.remote.origin.url with value https://github.com/qiao-zhi/springboot-ssm.git [INFO] Collected git.tags with value [INFO] evalCommit is [9120cf8905b7a6a44fbfe755c511b0602efc16e7] [INFO] Tag refs [[]] [INFO] Created map: [{}] [INFO] Collected git.closest.tag.name with value [INFO] evalCommit is [9120cf8905b7a6a44fbfe755c511b0602efc16e7] [INFO] Tag refs [[]] [INFO] Created map: [{}] [INFO] Collected git.closest.tag.commit.count with value [INFO] Collected git.total.commit.count with value 78 [INFO] Collected git.local.branch.ahead with value 0 [INFO] Collected git.local.branch.behind with value 0 [INFO] Collected git.build.time with value 20201114202916 [INFO] Collected git.build.version with value 0.0.1-SNAPSHOT [INFO] Collected git.build.host with value root [INFO] including property git.build.user.email in results [INFO] including property git.build.host in results [INFO] including property git.dirty in results [INFO] including property git.local.branch.behind in results [INFO] including property git.remote.origin.url in results [INFO] including property git.closest.tag.name in results [INFO] including property git.local.branch.ahead in results [INFO] including property git.total.commit.count in results [INFO] including property git.commit.id.describe-short in results [INFO] including property git.commit.user.email in results [INFO] including property git.commit.time in results [INFO] including property git.commit.message.full in results [INFO] including property git.build.version in results [INFO] including property git.commit.message.short in results [INFO] including property git.commit.id.abbrev in results [INFO] including property git.branch in results [INFO] including property git.build.user.name in results [INFO] including property git.closest.tag.commit.count in results [INFO] including property git.commit.id.describe in results [INFO] including property git.commit.id in results [INFO] including property git.tags in results [INFO] including property git.build.time in results [INFO] including property git.commit.user.name in results [INFO] Writing properties file to [E:\xiangmu\springboot-ssm\target\classes\git.properties] (for module springboot-ssm)... [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 16.472 s [INFO] Finished at: 2020-11-14T20:29:16+08:00 [INFO] Final Memory: 23M/245M [INFO] ------------------------------------------------------------------------
会在编译目录生成git.properties文件:
文件内容是git相关信息。内容大致如下:
#Generated by Git-Commit-Id-Plugin #Sat Nov 14 20:29:16 CST 2020 git.branch=master git.build.host=root git.build.time=20201114202916 git.build.user.email=qiao_liqiang@163.com git.build.user.name=qiaozhi git.build.version=0.0.1-SNAPSHOT git.closest.tag.commit.count= git.closest.tag.name= git.commit.id=9120cf8905b7a6a44fbfe755c511b0602efc16e7 git.commit.id.abbrev=9120cf8 git.commit.id.describe=9120cf8-dirty git.commit.id.describe-short=9120cf8-dirty git.commit.message.full=\u589E\u52A0git\u4FE1\u606F\u67E5\u770B\u63D2\u4EF6 git.commit.message.short=\u589E\u52A0git\u4FE1\u606F\u67E5\u770B\u63D2\u4EF6 git.commit.time=20201113140739 git.commit.user.email=954318308@qq.com git.commit.user.name=qqiaoliqiang git.dirty=true git.local.branch.ahead=0 git.local.branch.behind=0 git.remote.origin.url=https\://github.com/qiao-zhi/springboot-ssm.git git.tags= git.total.commit.count=78
build.host是build的计算机名称。下面是提交信息以及分支信息、总提交次数等信息。
可以通过Controller暴露信息,这样可以通过Controller查看打包信息。
(1)类信息如下:
package cn.qlq.git; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; /** * @author: 乔利强 * @date: 2020/11/13 12:45 * @description: */ @Configuration @PropertySource(value = "classpath:git.properties", ignoreResourceNotFound = true) public class BuildInfoProperties { @Autowired private Environment env; @Bean public BuildInfo getBuildInfo() { BuildInfo buildInfo = new BuildInfo(); buildInfo.gitDirty = env.getProperty("git.dirty"); buildInfo.gitRemoteOriginUrl = env.getProperty("git.remote.origin.url"); buildInfo.gitTags = env.getProperty("git.tags"); buildInfo.gitBranch = env.getProperty("git.branch"); buildInfo.gitCommitUserName = env.getProperty("git.commit.user.name"); buildInfo.gitCommitTime = env.getProperty("git.commit.time"); buildInfo.gitCommitMessageFull = env.getProperty("git.commit.message.full"); buildInfo.gitCommitId = env.getProperty("git.commit.id"); buildInfo.gitBuildVersion = env.getProperty("git.build.version"); buildInfo.gitBuildUserName = env.getProperty("git.build.user.name"); buildInfo.gitBuildTime = env.getProperty("git.build.time"); buildInfo.gitBuildHost = env.getProperty("git.build.host"); return buildInfo; } @Data public static class BuildInfo { private String gitDirty; private String gitRemoteOriginUrl; private String gitTags; private String gitBranch; private String gitCommitUserName; private String gitCommitTime; private String gitCommitMessageFull; private String gitCommitId; private String gitBuildVersion; private String gitBuildUserName; private String gitBuildTime; private String gitBuildHost; } }
Controller信息如下:
package cn.qlq.git; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author: 乔利强 * @date: 2020/11/13 12:46 * @description: */ @RestController public class BuildInfoController { @Autowired private BuildInfoProperties.BuildInfo buildInfo; @GetMapping(value = "/buildinfo", produces = {"application/json;charset=UTF-8"}) public String getBuildInfo() { return buildInfo.toString(); } }
(2)启动测试:
$ curl http://localhost:8088/buildinfo % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- 100 411 100 411 0 0 13258 0 --:--:-- --:--:-- --:--:-- 27400BuildInfoProperties.BuildInfo(gitDirty=true, gitRemoteOriginUrl=https://github.com/qiao-zhi/springboot-ssm.git, gitTags=, gitBranch=master, gitCommitUserName=qqiaoliqiang, gitCommitTime=20201113140739, gitCommitMessageFull=增加git信息查看插件, gitCommitId=9120cf8905b7a6a44fbfe755c511b0602efc16e7, gitBuildVersion=0.0.1-SNAPSHOT, gitBuildUserName=qiaozhi, gitBuildTime=20201114202916, gitBuildHost=root)
补充 :关于Environment 和 @PropertySource 的关系
Spring抽象了一个Environment来表示Spring应用程序环境配置,它整合了各种各样的外部环境,并且提供统一访问的方法。
@PropertySource 是Java Config方式的注解,其属性会自动注册到相应的Environment
@GetMapping(value = "/testEnv") public String testEnv() { String serverPort = env.getProperty("server.port"); String commitId = env.getProperty("git.commit.id"); return serverPort + "\t" + commitId; }
测试:Environment可以读到application.properties配置的信息和@PropertySource 读取的properties文件的信息
$ curl http://localhost:8088/testEnv % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- 100 45 100 45 0 0 64 0 --:--:-- --:--:-- --:--:-- 66 8088 9120cf8905b7a6a44fbfe755c511b0602efc16e7
spring的environment对象可以获取到java中系统属性和系统环境变量。也就是System.getenv(key) 可以获取到的环境变量和System.getProperty(key)可以获取到的属性。
2.配置打包名称, 可以从打包后文件查看commit的版本号
pom文件可以获取上面生成的git信息,类似于生成到pom文件中的propertis,可以在pom中${var}获取,也可以在application.yml 中用@var@ 获取。
1.修改pom中打包的版本信息
<version>0.0.1-SNAPSHOT-${git.commit.id.abbrev}</version>
2.执行package打包
结果:
[INFO] Building war: E:\xiangmu\springboot-ssm\target\springboot-ssm-0.0.1-SNAPSHOT-9120cf8.war
2. docker-maven-plugin 插件的使用
docker-maven-plugin 是为了帮助我们在Maven工程中,通过简单的配置,自动生成镜像并推送到仓库中。
git地址: https://github.com/spotify/docker-maven-plugin#use-a-dockerfile
1.配置DOCKER_HOST
docker-maven-plugin 插件默认连接本地 Docker 地址为:localhost:2375,所以我们需要先设置下环境变量。
可以通过如下命令查看:
$ docker-machine env default export DOCKER_TLS_VERIFY="1" export DOCKER_HOST="tcp://192.168.99.100:2376" export DOCKER_CERT_PATH="C:\Users\liqiang\.docker\machine\machines\default" export DOCKER_MACHINE_NAME="default" export COMPOSE_CONVERT_WINDOWS_PATHS="true" # Run this command to configure your shell: # eval $("E:\docker\Docker Toolbox\docker-machine.exe" env default)
最后在cmd执行如下:
SET DOCKER_TLS_VERIFY=1 SET DOCKER_HOST=tcp://192.168.99.100:2376 SET DOCKER_CERT_PATH=C:\Users\liqiang\.docker\machine\machines\default SET DOCKER_MACHINE_NAME=default SET COMPOSE_CONVERT_WINDOWS_PATHS=true
2.开始构建
构建镜像有两种方式。第一种是将构建信息指定到 POM 中,第二种是使用已存在的 Dockerfile 构建。第一种方式,支持将 FROM, ENTRYPOINT, CMD, MAINTAINER 以及 ADD 信息配置在 POM 中,不
需要使用 Dockerfile 配置。但是如果使用 VOLUME 或其他 Dockerfile 中的命令的时候,需要使用第二种方式,创建一个 Dockerfile,并在 POM 中配置 dockerDirectory 来指定路径即可。
1.方式一:pom.xml 指定
(1)pom中增加插件:
<build> <plugins> ... <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.2.2</version> <configuration> <imageName>springboot-ssm</imageName> <baseImage>hub.c.163.com/library/java:8-alpine</baseImage> <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint> <!-- copy the service's jar file from target into the root directory of the image --> <resources> <resource> <targetPath>/</targetPath> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> ... </plugins> </build>
(2)cmd到目录下执行如下命令:或者用IDEA提供的MAVEN插件也可以
mvn docker:build
(3) 执行成功后查看镜像
E:\xiangmu\springboot-ssm>docker images REPOSITORY TAG IMAGE ID CREATED SIZE springboot-ssm latest 1f5ab3f332ab 4 minutes ago 145MB hello-world latest bf756fb1ae65 10 months ago 13.3kB hub.c.163.com/library/rabbitmq management fb11f4e0a6b6 3 years ago 124MB hub.c.163.com/library/rabbitmq latest 88b79c465d96 3 years ago 124MB hub.c.163.com/library/java 8-alpine d991edd81416 3 years ago 145MB
(4) 启动镜像
docker run -d -p 8088:8088 springboot-ssm
2.方式二:使用Dockerfile(常见)
(1)修改pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.qlq</groupId> <artifactId>springboot-ssm</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <!-- <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 设置Tomcat打包的时候不打包下面配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<scope>provided</scope>--> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!--docker plugin--> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.2.2</version> <configuration> <imageName>springboot-ssm</imageName> <dockerDirectory>docker</dockerDirectory> </configuration> </plugin> </plugins> </build> </project>
和上面的功能等价。
(2) 新建文件 ${basedir}/docker/Dockerfile
FROM hub.c.163.com/library/java:8-alpine VOLUME /tmp ADD springboot-ssm-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java","-jar","/app.jar"]
springboot-ssm-0.0.1-SNAPSHOT.jar 是项目打的jar包,也可以用变量读取。
(3) 执行如下命令
mvn clean package docker:build
(4)启动脚本:
E:\xiangmu\springboot-ssm2>docker run -p 8088:8088 -t springboot-ssm . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.1.RELEASE)
-p参数意思是把容器里的808端口转到宿主机的8088端口上, -t是返回一个终端 .
注意:常见方式是基于基础镜像启动之后进入容器制作一些脚本,然后导出为镜像,然后将此镜像作为基础镜像
3. 打包源码的插件
执行mvn source:jar 可以打包,有时候希望package或者其他操作也将源码打包
<!-- 要将源码放上去,需要加入这个插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin>
测试的时候执行mvn clean package 查看target目录即可
4. 自动执行JUnit测试插件
maven-surefire-plugin 可以称为测试运行器(Test Runner),在mvn package、install 时会自动执行单元测试。在默认情况下,maven-surefire-plugin的test目标会自动执行测试源码路径(默认为src/test/java/)下所有符合一组命名模式的测试类。这组模式为:
(1)**/Test*.java:任何子目录下所有命名以Test开关的Java类。
(2)**/*Test.java:任何子目录下所有命名以Test结尾的Java类。
(3)**/*TestCase.java:任何子目录下所有命名以TestCase结尾的Java类。
<!-- 执行Junit测试(测试所有类) --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version> <configuration> <includes> <!--<include>*\*\*\*Test.java</include>--> <include>**\*</include> </includes> </configuration> </plugin>
然后执行mvn test。 或者执行package、install等操作都会执行Junit测试。如果JUnit测试不通过会报错,比如如下测试代码:
@Test public void test1() { System.out.println("******************************************"); System.out.println("=========================================="); System.out.println(1 / 0); }
执行 mvn clean package后日志如下:
$ mvn clean package [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building bx 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ bx --- [INFO] Deleting E:\xiangmu\bs-media\media-server\target [INFO] [INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ bx --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 2 resources [INFO] Copying 4 resources [INFO] [INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ bx --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 179 source files to E:\xiangmu\bs-media\media-server\target\classes [INFO] /E:/xiangmu/bs-media/media-server/src/main/java/com/xm/ggn/bean/AbstractEntity.java: 某些输入文件使用或覆盖了已过时的 API。 [INFO] /E:/xiangmu/bs-media/media-server/src/main/java/com/xm/ggn/bean/AbstractEntity.java: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。 [INFO] /E:/xiangmu/bs-media/media-server/src/main/java/com/xm/ggn/utils/export/ExcelExporter.java: 某些输入文件使用了未经检查或不安全的操作。 [INFO] /E:/xiangmu/bs-media/media-server/src/main/java/com/xm/ggn/utils/export/ExcelExporter.java: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。 [INFO] [INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ bx --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ bx --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 3 source files to E:\xiangmu\bs-media\media-server\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.10:test (default-test) @ bx --- [INFO] Surefire report directory: E:\xiangmu\bs-media\media-server\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running guava.TestGuava ****************************************** ========================================== Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.199 sec <<< FAILURE! Results : Tests in error: test1(guava.TestGuava): / by zero Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 33.759 s [INFO] Finished at: 2021-02-05T19:42:05+08:00 [INFO] Final Memory: 55M/472M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-test) on project bx: There are test failures. [ERROR] [ERROR] Please refer to E:\xiangmu\bs-media\media-server\target\surefire-reports for the individual test results. [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
如果想跳过JUnit测试,可以使用:-DskipTests 参数,比如:
mvn clean package -DskipTests
补充:也可以生成测试报告
mvn cobertura:cobertura
会生成报告到target/surefire-reports 目录下。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-11-14 SpringTask定时任务的使用
2017-11-14 Mysql中Group By使用Having语句配合查询(where和having区别)
2017-11-14 jQuery.form.js使用
2017-11-14 JQuery中如何重置(reset)表单(且清空隐藏域)