Maven插件学习(三)——插件配置依赖和执行目标
maven-checkstyle-plugin插件的配置
配置了两个依赖和一个执行任务。
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-checkstyle-plugin</artifactId><version>2.17</version><dependencies><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId> <!-- 将commons-logging桥接到 SLF4J --><version>1.7.5</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-jdk14</artifactId> <!-- 将SLF4J绑定到JDK的java.util.logging--><version>1.7.5</version></dependency></dependencies><executions><execution><id>checkstyle-validation</id><phase>process-sources</phase><configuration><encoding>UTF-8</encoding><consoleOutput>true</consoleOutput><failsOnError>true</failsOnError><linkXRef>false</linkXRef><configLocation>../checkstyle_checks.xml</configLocation></configuration><goals><goal>check</goal></goals></execution></executions>
</plugin>
执行目标说明
cmd中执行以下命令,查看插件的详细说明
mvn help:describe -Dplugin=org.apache.maven.plugins:maven-checkstyle-plugin:2.17 -Ddetail
mvn help:describe -Dplugin=org.apache.maven.plugins:maven-checkstyle-plugin:2.17 -Ddetail[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] --- maven-help-plugin:3.4.0:describe (default-cli) @ standalone-pom ---
[INFO] org.apache.maven.plugins:maven-checkstyle-plugin:2.17Name: Apache Maven Checkstyle Plugin
Description: Generates a report on violations of code style and optionallyfails the build if violations are detected.
Group Id: org.apache.maven.plugins
Artifact Id: maven-checkstyle-plugin
Version: 2.17
Goal Prefix: checkstyleThis plugin has 4 goals:checkstyle:checkDescription: Performs Checkstyle analysis and outputs violations or a countof violations to the console, potentially failing the build. It can also beconfigured to re-use an earlier analysis.Implementation:org.apache.maven.plugin.checkstyle.CheckstyleViolationCheckMojoLanguage: javaBound to phase: verifyAvailable parameters:cacheFile (Default:${project.build.directory}/checkstyle-cachefile)Specifies the cache file used to speed up Checkstyle on successive runs.checkstyleRulesBy using this property, you can specify the whole Checkstyle rules inlinedirectly inside this pom. This feature requires Maven 3+. <plugin> ...<configuration> <checkstyleRules> <module name="Checker"> <modulename="FileTabCharacter"> <property name="eachLine" value="true" /></module> <module name="TreeWalker"> <module name="EmptyBlock"/></module> </module> </checkstyleRules> </configuration> ...configLocation (Default: sun_checks.xml)User property: checkstyle.config.locationSpecifies the location of the XML configuration to use.Potential values are a filesystem path, a URL, or a classpath resource.This parameter expects that the contents of the location conform to thexml format (Checkstyle Checker module<http://checkstyle.sourceforge.net/config.html#Modules>) configuration ofrulesets.This parameter is resolved as resource, URL, then file. If successfullyresolved, the contents of the configuration is copied into the${project.build.directory}/checkstyle-configuration.xml file before beingpassed to Checkstyle as a configuration.There are 2 predefined rulesets.* sun_checks.xml: Sun Checks.* google_checks.xml: Google Checks.consoleOutput (Default: false)User property: checkstyle.consoleOutputOutput errors to console.encoding (Default: ${project.build.sourceEncoding})User property: encodingThe file encoding to use when reading the source files. If the propertyproject.build.sourceEncoding is not set, the platform default encoding isused. Note: This parameter always overrides the property charset fromCheckstyle's TreeWalker module.excludesUser property: checkstyle.excludesSpecifies the names filter of the source files to be excluded forCheckstyle.failOnViolation (Default: true)User property: checkstyle.failOnViolationFail the build on a violation. The goal checks for the violations afterlogging them (if {@link #logViolationsToConsole} is {@code true}).Compare this to {@link #failsOnError} which fails the build immediatelybefore examining the output log.failsOnError (Default: false)If this is true, and Checkstyle reported any violations or errors, thebuild fails immediately after running Checkstyle, before checking the logfor {@link #logViolationsToConsole}. If you want to use {@link#logViolationsToConsole}, use {@link #failOnViolation} instead of this.headerLocation (Default: LICENSE.txt)User property: checkstyle.header.fileSpecifies the location of the License file (a.k.a. the header file) thatcan be used by Checkstyle to verify that source code has the correctlicense header.You need to use ${checkstyle.header.file} in your Checkstyle xmlconfiguration to reference the name of this header file.For instance:<module name="RegexpHeader"> <property name="headerFile"value="${checkstyle.header.file}"/> </module>includeResources (Default: true)Required: trueUser property: checkstyle.includeResourcesWhether to apply Checkstyle to resource directories.includes (Default: **\/*.java)Required: trueUser property: checkstyle.includesSpecifies the names filter of the source files to be used for Checkstyle.includeTestResources (Default: true)Required: trueUser property: checkstyle.includeTestResourcesWhether to apply Checkstyle to test resource directories.includeTestSourceDirectory (Default: false)Include or not the test source directory to be used for Checkstyle.logViolationsToConsole (Default: true)User property: checkstyle.consoleOutput the detected violations to the console.maxAllowedViolations (Default: 0)User property: checkstyle.maxAllowedViolationsThe maximum number of allowed violations. The execution fails only if thenumber of violations is above this limit.outputFile (Default:${project.build.directory}/checkstyle-result.xml)User property: checkstyle.output.fileSpecifies the path and filename to save the Checkstyle output. The formatof the output file is determined by the outputFileFormat parameter.outputFileFormat (Default: xml)User property: checkstyle.output.formatSpecifies the format of the output to be used when writing to the outputfile. Valid values are "plain" and "xml".propertiesLocationUser property: checkstyle.properties.locationSpecifies the location of the properties file.This parameter is resolved as URL, File then resource. If successfullyresolved, the contents of the properties location is copied into the${project.build.directory}/checkstyle-checker.properties file beforebeing passed to Checkstyle for loading.The contents of the propertiesLocation will be made available toCheckstyle for specifying values for parameters within the xmlconfiguration (specified in the configLocation parameter).propertyExpansionAllows for specifying raw property expansion information.resourceExcludesUser property: checkstyle.resourceExcludesSpecifies the names filter of the files to be excluded for Checkstylewhen checking resources.resourceIncludes (Default: **/*.properties)Required: trueUser property: checkstyle.resourceIncludesSpecifies the names filter of the files to be used for Checkstyle whenchecking resources.rulesFiles (Default:${project.build.directory}/checkstyle-rules.xml)User property: checkstyle.output.rules.filedump file for inlined Checkstyle rulesskip (Default: false)User property: checkstyle.skipSkip entire check.skipExec (Default: false)User property: checkstyle.skipExecSkip Checkstyle execution will only scan the outputFile.sourceDirectories (Default: ${project.compileSourceRoots})Specifies the location of the source directories to be used forCheckstyle.sourceDirectorySpecifies the location of the source directory to be used for Checkstyle.Deprecated. instead use {@link #sourceDirectories}suppressionsFileExpression (Default:checkstyle.suppressions.file)User property: checkstyle.suppression.expressionThe key to be used in the properties for the suppressions file.suppressionsLocationUser property: checkstyle.suppressions.locationSpecifies the location of the suppressions XML file to use.This parameter is resolved as resource, URL, then file. If successfullyresolved, the contents of the suppressions XML is copied into the${project.build.directory}/checkstyle-suppressions.xml file before beingpassed to Checkstyle for loading.See suppressionsFileExpression for the property that will be madeavailable to your Checkstyle configuration.testSourceDirectories (Default:${project.testCompileSourceRoots})Specifies the location of the test source directories to be used forCheckstyle.testSourceDirectorySpecifies the location of the test source directory to be used forCheckstyle.Deprecated. instead use {@link #testSourceDirectories}useFileIf null, the Checkstyle plugin will display violations on stdout.Otherwise, a text file will be created with the violations.violationIgnoreUser property: checkstyle.violation.ignoreViolations to ignore. This is a comma-separated list, each value beingeither a rule name, a rule category or a java package name of rule class.violationSeverity (Default: error)User property: checkstyle.violationSeverityThe lowest severity level that is considered a violation. Valid valuesare "error", "warning" and "info".checkstyle:checkstyleDescription: A reporting task that performs Checkstyle analysis andgenerates an HTML report on any violations that Checkstyle finds.Note: This goal should be used as a Maven report.Implementation: org.apache.maven.plugin.checkstyle.CheckstyleReportLanguage: javaAvailable parameters:cacheFile (Default:${project.build.directory}/checkstyle-cachefile)Specifies the cache file used to speed up Checkstyle on successive runs.configLocation (Default: sun_checks.xml)User property: checkstyle.config.locationSpecifies the location of the XML configuration to use.Potential values are a filesystem path, a URL, or a classpath resource.This parameter expects that the contents of the location conform to thexml format (Checkstyle Checker module<http://checkstyle.sourceforge.net/config.html#Modules>) configuration ofrulesets.This parameter is resolved as resource, URL, then file. If successfullyresolved, the contents of the configuration is copied into the${project.build.directory}/checkstyle-configuration.xml file before beingpassed to Checkstyle as a configuration.There are 2 predefined rulesets included in Maven Checkstyle Plugin:* sun_checks.xml: Sun Checks.* google_checks.xml: Google Checks.consoleOutput (Default: false)User property: checkstyle.consoleOutputOutput errors to console.enableFilesSummary (Default: true)User property: checkstyle.enable.files.summarySpecifies if the Files summary should be enabled or not.enableRSS (Default: true)User property: checkstyle.enable.rssSpecifies if the RSS should be enabled or not.enableRulesSummary (Default: true)User property: checkstyle.enable.rules.summarySpecifies if the Rules summary should be enabled or not.enableSeveritySummary (Default: true)User property: checkstyle.enable.severity.summarySpecifies if the Severity summary should be enabled or not.encoding (Default: ${project.build.sourceEncoding})User property: encodingThe file encoding to use when reading the source files. If the propertyproject.build.sourceEncoding is not set, the platform default encoding isused. Note: This parameter always overrides the property charset fromCheckstyle's TreeWalker module.excludesUser property: checkstyle.excludesSpecifies the names filter of the source files to be excluded forCheckstyle.failsOnError (Default: false)Specifies if the build should fail upon a violation.format (Default: sun)Specifies what predefined check set to use. Available sets are "sun" (forthe Sun coding conventions), and "maven".Deprecated. Use configLocation instead.headerFile (Default: ${basedir}/LICENSE.txt)Specifies the location of the License file (a.k.a. the header file) thatis used by Checkstyle to verify that source code has the correct licenseheader.Deprecated. Use headerLocation instead.headerLocation (Default: LICENSE.txt)User property: checkstyle.header.fileSpecifies the location of the License file (a.k.a. the header file) thatcan be used by Checkstyle to verify that source code has the correctlicense header.You need to use ${checkstyle.header.file} in your Checkstyle xmlconfiguration to reference the name of this header file.For instance:<module name="RegexpHeader"> <property name="headerFile"value="${checkstyle.header.file}"/> </module>includeResources (Default: true)Required: trueUser property: checkstyle.includeResourcesSpecifies whether to include the resource directories in the check.includes (Default: **\/*.java)Required: trueUser property: checkstyle.includesSpecifies the names filter of the source files to be used for Checkstyle.includeTestResources (Default: true)Required: trueUser property: checkstyle.includeTestResourcesSpecifies whether to include the test resource directories in the check.includeTestSourceDirectory (Default: false)Include or not the test source directory/directories to be used forCheckstyle.linkXRef (Default: true)User property: linkXRefLink the violation line numbers to the source xref. Will linkautomatically if Maven JXR plugin is being used.outputFile (Default:${project.build.directory}/checkstyle-result.xml)User property: checkstyle.output.fileSpecifies the path and filename to save the Checkstyle output. The formatof the output file is determined by the outputFileFormat parameter.outputFileFormat (Default: xml)User property: checkstyle.output.formatSpecifies the format of the output to be used when writing to the outputfile. Valid values are "plain" and "xml".packageNamesFileSpecifies the location of the package names XML to be used to configureCheckstyle.Deprecated. Use packageNamesLocation instead.packageNamesLocationSpecifies the location of the package names XML to be used to configurethe Checkstyle Packages<http://checkstyle.sourceforge.net/config.html#Packages>.This parameter is resolved as resource, URL, then file. If resolved to aresource, or a URL, the contents of the package names XML is copied intothe ${project.build.directory}/checkstyle-packagenames.xml file beforebeing passed to Checkstyle for loading.propertiesFileSpecifies the location of the Checkstyle properties file that will beused to check the source.Deprecated. Use propertiesLocation instead.propertiesLocationUser property: checkstyle.properties.locationSpecifies the location of the properties file.This parameter is resolved as URL, File then resource. If successfullyresolved, the contents of the properties location is copied into the${project.build.directory}/checkstyle-checker.properties file beforebeing passed to Checkstyle for loading.The contents of the propertiesLocation will be made available toCheckstyle for specifying values for parameters within the xmlconfiguration (specified in the configLocation parameter).propertiesURLSpecifies the URL of the Checkstyle properties that will be used to checkthe source.Deprecated. Use propertiesLocation instead.propertyExpansionAllows for specifying raw property expansion information.resourceExcludesUser property: checkstyle.resourceExcludesSpecifies the names filter of the resource files to be excluded forCheckstyle.resourceIncludes (Default: **/*.properties)Required: trueUser property: checkstyle.resourceIncludesSpecifies the names filter of the resource files to be used forCheckstyle.skip (Default: false)User property: checkstyle.skipSkip entire check.sourceDirectories (Default: ${project.compileSourceRoots})Specifies the location of the source directories to be used forCheckstyle.sourceDirectorySpecifies the location of the source directory to be used for Checkstyle.Deprecated. instead use {@link #sourceDirectories}suppressionsFileSpecifies the location of the suppressions XML file to use. The plugindefines a Checkstyle property named checkstyle.suppressions.file with thevalue of this property. This allows using the Checkstyle property in yourown custom Checkstyle configuration file when specifying a suppressionsfile.Deprecated. Use suppressionsLocation instead.suppressionsFileExpression (Default:checkstyle.suppressions.file)User property: checkstyle.suppression.expressionThe key to be used in the properties for the suppressions file.suppressionsLocationUser property: checkstyle.suppressions.locationSpecifies the location of the suppressions XML file to use.This parameter is resolved as resource, URL, then file. If successfullyresolved, the contents of the suppressions XML is copied into the${project.build.directory}/checkstyle-supressions.xml file before beingpassed to Checkstyle for loading.See suppressionsFileExpression for the property that will be madeavailable to your Checkstyle configuration.testSourceDirectories (Default:${project.testCompileSourceRoots})Specifies the location of the test source directories to be used forCheckstyle.testSourceDirectorySpecifies the location of the test source directory to be used forCheckstyle.Deprecated. instead use {@link #testSourceDirectories}treeWalkerNamesWhen using custom treeWalkers, specify their names here so the checksinside the treeWalker end up the the rule-summary.useFileIf null, the Checkstyle plugin will display violations on stdout.Otherwise, a text file will be created with the violations.xrefLocation (Default:${project.reporting.outputDirectory}/xref)Location of the Xrefs to link to.checkstyle:checkstyle-aggregateDescription: A reporting task that performs Checkstyle analysis andgenerates an aggregate HTML report on the violations that Checkstyle findsin a multi-module reactor build.Note: This goal should be used as a Maven report.Implementation: org.apache.maven.plugin.checkstyle.CheckstyleAggregateReportLanguage: javaAvailable parameters:cacheFile (Default:${project.build.directory}/checkstyle-cachefile)Specifies the cache file used to speed up Checkstyle on successive runs.configLocation (Default: sun_checks.xml)User property: checkstyle.config.locationSpecifies the location of the XML configuration to use.Potential values are a filesystem path, a URL, or a classpath resource.This parameter expects that the contents of the location conform to thexml format (Checkstyle Checker module<http://checkstyle.sourceforge.net/config.html#Modules>) configuration ofrulesets.This parameter is resolved as resource, URL, then file. If successfullyresolved, the contents of the configuration is copied into the${project.build.directory}/checkstyle-configuration.xml file before beingpassed to Checkstyle as a configuration.There are 2 predefined rulesets included in Maven Checkstyle Plugin:* sun_checks.xml: Sun Checks.* google_checks.xml: Google Checks.consoleOutput (Default: false)User property: checkstyle.consoleOutputOutput errors to console.enableFilesSummary (Default: true)User property: checkstyle.enable.files.summarySpecifies if the Files summary should be enabled or not.enableRSS (Default: true)User property: checkstyle.enable.rssSpecifies if the RSS should be enabled or not.enableRulesSummary (Default: true)User property: checkstyle.enable.rules.summarySpecifies if the Rules summary should be enabled or not.enableSeveritySummary (Default: true)User property: checkstyle.enable.severity.summarySpecifies if the Severity summary should be enabled or not.encoding (Default: ${project.build.sourceEncoding})User property: encodingThe file encoding to use when reading the source files. If the propertyproject.build.sourceEncoding is not set, the platform default encoding isused. Note: This parameter always overrides the property charset fromCheckstyle's TreeWalker module.excludesUser property: checkstyle.excludesSpecifies the names filter of the source files to be excluded forCheckstyle.failsOnError (Default: false)Specifies if the build should fail upon a violation.headerLocation (Default: LICENSE.txt)User property: checkstyle.header.fileSpecifies the location of the License file (a.k.a. the header file) thatcan be used by Checkstyle to verify that source code has the correctlicense header.You need to use ${checkstyle.header.file} in your Checkstyle xmlconfiguration to reference the name of this header file.For instance:<module name="RegexpHeader"> <property name="headerFile"value="${checkstyle.header.file}"/> </module>includeResources (Default: true)Required: trueUser property: checkstyle.includeResourcesSpecifies whether to include the resource directories in the check.includes (Default: **\/*.java)Required: trueUser property: checkstyle.includesSpecifies the names filter of the source files to be used for Checkstyle.includeTestResources (Default: true)Required: trueUser property: checkstyle.includeTestResourcesSpecifies whether to include the test resource directories in the check.includeTestSourceDirectory (Default: false)Include or not the test source directory/directories to be used forCheckstyle.linkXRef (Default: true)User property: linkXRefLink the violation line numbers to the source xref. Will linkautomatically if Maven JXR plugin is being used.outputFile (Default:${project.build.directory}/checkstyle-result.xml)User property: checkstyle.output.fileSpecifies the path and filename to save the Checkstyle output. The formatof the output file is determined by the outputFileFormat parameter.outputFileFormat (Default: xml)User property: checkstyle.output.formatSpecifies the format of the output to be used when writing to the outputfile. Valid values are "plain" and "xml".propertiesLocationUser property: checkstyle.properties.locationSpecifies the location of the properties file.This parameter is resolved as URL, File then resource. If successfullyresolved, the contents of the properties location is copied into the${project.build.directory}/checkstyle-checker.properties file beforebeing passed to Checkstyle for loading.The contents of the propertiesLocation will be made available toCheckstyle for specifying values for parameters within the xmlconfiguration (specified in the configLocation parameter).propertyExpansionAllows for specifying raw property expansion information.resourceExcludesUser property: checkstyle.resourceExcludesSpecifies the names filter of the resource files to be excluded forCheckstyle.resourceIncludes (Default: **/*.properties)Required: trueUser property: checkstyle.resourceIncludesSpecifies the names filter of the resource files to be used forCheckstyle.skip (Default: false)User property: checkstyle.skipSkip entire check.sourceDirectories (Default: ${project.compileSourceRoots})Specifies the location of the source directories to be used forCheckstyle.sourceDirectorySpecifies the location of the source directory to be used for Checkstyle.Deprecated. instead use {@link #sourceDirectories}suppressionsFileExpression (Default:checkstyle.suppressions.file)User property: checkstyle.suppression.expressionThe key to be used in the properties for the suppressions file.suppressionsLocationUser property: checkstyle.suppressions.locationSpecifies the location of the suppressions XML file to use.This parameter is resolved as resource, URL, then file. If successfullyresolved, the contents of the suppressions XML is copied into the${project.build.directory}/checkstyle-supressions.xml file before beingpassed to Checkstyle for loading.See suppressionsFileExpression for the property that will be madeavailable to your Checkstyle configuration.testSourceDirectories (Default:${project.testCompileSourceRoots})Specifies the location of the test source directories to be used forCheckstyle.testSourceDirectorySpecifies the location of the test source directory to be used forCheckstyle.Deprecated. instead use {@link #testSourceDirectories}treeWalkerNamesWhen using custom treeWalkers, specify their names here so the checksinside the treeWalker end up the the rule-summary.useFileIf null, the Checkstyle plugin will display violations on stdout.Otherwise, a text file will be created with the violations.xrefLocation (Default:${project.reporting.outputDirectory}/xref)Location of the Xrefs to link to.checkstyle:helpDescription: Display help information on maven-checkstyle-plugin.Call mvn checkstyle:help -Ddetail=true -Dgoal=<goal-name> to displayparameter details.Implementation: org.apache.maven.plugin.checkstyle.HelpMojoLanguage: javaAvailable parameters:detail (Default: false)User property: detailIf true, display all settable properties for each goal.goalUser property: goalThe name of the goal for which to show help. If unspecified, all goalswill be displayed.indentSize (Default: 2)User property: indentSizeThe number of spaces per indentation level, should be positive.lineLength (Default: 80)User property: lineLengthThe maximum length of a display line, should be positive.[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18.494 s
[INFO] Finished at: 2025-04-22T10:32:23+08:00
[INFO] ------------------------------------------------------------------------
根据插件的说明可以看到插件的前缀是checkstyle,有4个目标
checkstyle:check 绑定到default生命周期的verify阶段
checkstyle:checkstyle 没有默认绑定
checkstyle:checkstyle-aggregate 没有默认绑定
checkstyle:help 没有默认绑定
插件中excution执行 checkstyle:check
目标,对源代码进行静态代码检查,将插件执行绑定到 Maven 生命周期的 process-sources
阶段(即编译前),如果不配置 <execution>
,插件会绑定到 verify
生命周期阶段。此处显式声明后,会覆盖默认绑定。configuration指定了excution的配置
<configuration><encoding>UTF-8</encoding> <!-- 指定文件编码 --><consoleOutput>true</consoleOutput> <!-- 在控制台输出检查结果 --><failsOnError>true</failsOnError> <!-- 检查失败时终止构建 --><linkXRef>false</linkXRef> <!-- 不生成交叉引用报告 --><configLocation>../checkstyle_checks.xml</configLocation> <!-- 规则文件路径 -->
</configuration>
配置依赖说明
强制 maven-checkstyle-plugin
使用特定的日志框架组合,避免因日志实现冲突导致插件执行异常或无日志输出。
什么鬼情况下Maven插件配置中需要单独声明 <dependencies>
呢?
1. 覆盖插件默认的依赖版本
插件的默认依赖可能:
-
版本过旧(存在安全漏洞或需要新特性)
-
版本冲突(与项目其他依赖不兼容)
2. 添加插件缺失的依赖
某些插件可能:
-
按需加载依赖(未包含在默认打包中)
-
需要额外库支持(如数据库驱动、扩展工具)
示例场景:
如果 maven-checkstyle-plugin
需要连接数据库校验规则,但未内置 JDBC 驱动,就需要手动添加:
<dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency>
</dependencies>
3. 解决类加载隔离问题
Maven 插件的依赖与项目依赖是隔离的(避免冲突)。如果插件需要访问项目中的类或第三方库,必须显式声明依赖。
maven-checkstyle-plugin中jcl-over-slf4j
和 slf4j-jdk14
是为了:
-
统一日志框架(避免插件使用
commons-logging
,而是重定向到SLF4J
) -
确保插件日志输出与项目一致(如都输出到
java.util.logging
)。
4. 替换插件的默认实现
某些插件允许通过依赖替换核心组件。例如:
-
替换代码分析器的规则引擎
-
更换模板渲染工具