補充幾個maven經常使用的插件。java
官網:https://github.com/git-commit-id/git-commit-id-maven-plugingit
這個插件在分佈式部署環境很是有用,能夠經過此插件看出打包所處的git環境,分支、倉庫、提交的head信息等。github
包含兩個目標:web
1.git-commit-id:revision:將構建時的信息保存到指定文件中或maven的屬性中。spring
2.git-commit-id:validateRevision:校驗屬性是否符合預期值,默認綁定階段:verify。(這個不經常使用)docker
<!-- 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>
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文件:shell
文件內容是git相關信息。內容大體以下:apache
#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的計算機名稱。下面是提交信息以及分支信息、總提交次數等信息。json
能夠經過Controller暴露信息,這樣能夠經過Controller查看打包信息。tomcat
(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)能夠獲取到的屬性。
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
docker-maven-plugin 是爲了幫助咱們在Maven工程中,經過簡單的配置,自動生成鏡像並推送到倉庫中。
git地址: https://github.com/spotify/docker-maven-plugin#use-a-dockerfile
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
構建鏡像有兩種方式。第一種是將構建信息指定到 POM 中,第二種是使用已存在的 Dockerfile 構建。第一種方式,支持將 FROM, ENTRYPOINT, CMD, MAINTAINER 以及 ADD 信息配置在 POM 中,不
須要使用 Dockerfile 配置。可是若是使用 VOLUME 或其餘 Dockerfile 中的命令的時候,須要使用第二種方式,建立一個 Dockerfile,並在 POM 中配置 dockerDirectory 來指定路徑便可。
(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
(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是返回一個終端 .
注意:常見方式是基於基礎鏡像啓動以後進入容器製做一些腳本,而後導出爲鏡像,而後將此鏡像做爲基礎鏡像
執行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目錄便可
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 目錄下。