zno2

29) resources:resources 如何把pom中属性动态使用到java中

http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

http://maven.apache.org/plugins/maven-resources-plugin/index.html

http://maven.apache.org/plugins-archives/maven-resources-plugin-2.7/resources-mojo.html

 

效果就是改源码。

啥时候改?可以通过插件直接改,也可以通过maven phase 改

怎么改?目标文本文件中包含 ${...} 

拿什么改? 四种属性

如何控制范围? 通过include exclude 进行配置

Required Parameters

NameTypeSinceDescription
outputDirectory File - The output directory into which to copy the resources.
Default value is${project.build.outputDirectory}.

Optional Parameters

NameTypeSinceDescription
delimiters List 2.4

Set of delimiters for expressions to filter within the resources. These delimiters are specified in the form 'beginToken*endToken'. If no '*' is given, the delimiter is assumed to be the same for start and end.

So, the default filtering delimiters might be specified as:

<delimiters>
  <delimiter>${*}</delimiter>
  <delimiter>@</delimiter>
</delimiters>

Since the '@' delimiter is the same on both ends, we don't need to specify '@*@' (though we can).

encoding String - The character encoding scheme to be applied when filtering resources.
Default value is${project.build.sourceEncoding}.
User property isencoding.
escapeString String 2.3 Expression preceded with the String won't be interpolated \${foo} will be replaced with ${foo}
User property ismaven.resources.escapeString.
escapeWindowsPaths boolean 2.4 Whether to escape backslashes and colons in windows-style paths.
Default value istrue.
User property ismaven.resources.escapeWindowsPaths.
filters List - The list of extra filter properties files to be used along with System properties, project properties, and filter properties files specified in the POM build/filters section, which should be used for the filtering during the current mojo execution. 
Normally, these will be configured from a plugin's execution section, to provide a different set of filters for a particular execution. For instance, starting in Maven 2.2.0, you have the option of configuring executions with the id's default-resources and default-testResources to supply different configurations for the two different types of resources. By supplying extraFiltersconfigurations, you can separate which filters are used for which type of resource.
includeEmptyDirs boolean 2.3 Copy any empty directories included in the Resources.
Default value isfalse.
User property ismaven.resources.includeEmptyDirs.
mavenFilteringHints List 2.4

List of plexus components hint which implements MavenResourcesFiltering.filterResources(). They will be executed after the resources copying/filtering.

nonFilteredFileExtensions List 2.3 Additional file extensions to not apply filtering (already defined are : jpg, jpeg, gif, bmp, png)
overwrite boolean 2.3 Overwrite existing files even if the destination files are newer.
Default value isfalse.
User property ismaven.resources.overwrite.
supportMultiLineFiltering boolean 2.5 stop searching endToken at the end of line
Default value isfalse.
User property ismaven.resources.supportMultiLineFiltering.
useBuildFilters boolean 2.4 If false, don't use the filters specified in the build/filters section of the POM when processing resources in this mojo execution. 
See also: ResourcesMojo.buildFilters and ResourcesMojo.filters
Default value istrue.
useDefaultDelimiters boolean 2.4 (no description)
Default value istrue. 解释一下,如果是true则可以额外使用默认的两种'@' 和 '${*}' ,如果是false 则不可以使用默认的

 

关于delimiters 如何自定义:

元素中值的格式:     开始符*结束符

如果没有星号,则认为给定的值是开始符,并且也是结束符

举例:

<delimiter>#{*}</delimiter>  

<delimiter>||</delimiter>

<delimiter>{{*}}</delimiter>

 

奇怪的问题,执行后 ${} 没有被替换,-X 详细日志 发现 resource.delimiter=@

原因:没有指定 useDefaultDelimiters ,指定后还是 @ 不过${}可以被替换了,怪异!保险起见可以主动指定<delimiter>${*}</delimiter>

注意:如果想要使用'{{*}}' 不要配置成'{{' ,因为不对称,实际使用时是'{{someproperty}}' ,而不是'{{someproperty{{'

方式一:使用默认'@'和'${*}' ,不推荐,容易和spring 中的混淆

             <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <encoding>utf-8</encoding>
                    <useDefaultDelimiters>true</useDefaultDelimiters>
                </configuration>
                <executions>
                    <execution>
                        <phase>process-sources</phase>
                        <goals>
                            <goal>resources</goal>
                        </goals>
                        <configuration>
                            <resources>
                                <resource>
                                    <filtering>true</filtering>
                                    <directory>src/main/resources</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

 

执行 mvn process-sources 

方式二(简化形式,但是要注意mvn命令发生了变化):

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>utf-8</encoding>
                    <useDefaultDelimiters>true</useDefaultDelimiters>
                </configuration>
            </plugin>
        </plugins>
    </build>

 

执行 mvn resources:resources

 

支持 profile

     <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
  <profiles>
        <profile>
            <id>DEV</id>
            <properties>
                <changethis>aaaaaaaaaaaaaa</changethis>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>PRO</id>
            <properties>
                <changethis>bbbbbbbbbbbbb</changethis>
            </properties>
        </profile>
    </profiles>
    

 目标文件 src/main/resources/bootstrap.yml

a: ${changethis}

 

执行   mvn resources:resources -PPRO -X 

Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-25T02:41:47+08:00)
Maven home: D:\e\maven\apache-maven-3.6.0\bin\..
Java version: 1.8.0_181-1-redhat, vendor: Oracle Corporation, runtime: D:\e\Java\openjdk1.8.0_181\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
[DEBUG] Created new class realm maven.api
...
[DEBUG] Populating class realm maven.api
[INFO] Error stacktraces are turned on.
[DEBUG] Message scheme: color
[DEBUG] Message styles: debug info warning error success failure strong mojo project
[DEBUG] Reading global settings from D:\e\maven\apache-maven-3.6.0\bin\..\conf\settings.xml
[DEBUG] Reading user settings from C:\Users\witas\.m2\settings.xml
[DEBUG] Reading global toolchains from D:\e\maven\apache-maven-3.6.0\bin\..\conf\toolchains.xml
[DEBUG] Reading user toolchains from C:\Users\witas\.m2\toolchains.xml
[DEBUG] Using local repository at D:\mvnrepository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10.0 for D:\mvnrepository
[INFO] Scanning for projects...
[DEBUG] Extension realms for project cn.zno:ztest:jar:0.0.1-SNAPSHOT: (none)
[DEBUG] Looking up lifecycle mappings for packaging jar from ClassRealm[plexus.core, parent: null]
[DEBUG] Resolving plugin prefix resources from [org.apache.maven.plugins, org.codehaus.mojo]
[DEBUG] Resolved plugin prefix resources to org.apache.maven.plugins:maven-resources-plugin from POM cn.zno:ztest:jar:0.0.1-SNAPSHOT
[DEBUG] === REACTOR BUILD PLAN ================================================
[DEBUG] Project: cn.zno:ztest:jar:0.0.1-SNAPSHOT
[DEBUG] Tasks:   [resources:resources]
[DEBUG] Style:   Regular
[DEBUG] =======================================================================
[INFO] 
[INFO] ----------------------------< cn.zno:ztest >----------------------------
[INFO] Building ztest 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[DEBUG] Resolving plugin prefix resources from [org.apache.maven.plugins, org.codehaus.mojo]
[DEBUG] Resolved plugin prefix resources to org.apache.maven.plugins:maven-resources-plugin from POM cn.zno:ztest:jar:0.0.1-SNAPSHOT
[DEBUG] Lifecycle default -> [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]
[DEBUG] Lifecycle clean -> [pre-clean, clean, post-clean]
[DEBUG] Lifecycle site -> [pre-site, site, post-site, site-deploy]
[DEBUG] === PROJECT BUILD PLAN ================================================
[DEBUG] Project:       cn.zno:ztest:0.0.1-SNAPSHOT
[DEBUG] Dependencies (collect): []
[DEBUG] Dependencies (resolve): []
[DEBUG] Repositories (dependencies): [nexus (http://192.168.3.57:8881/nexus/content/groups/public/, default, releases+snapshots), central (https://repo.maven.apache.org/maven2, default, releases)]
[DEBUG] Repositories (plugins)     : [central (https://repo.maven.apache.org/maven2, default, releases)]
[DEBUG] -----------------------------------------------------------------------
[DEBUG] Goal:          org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-cli)
[DEBUG] Style:         Regular
[DEBUG] Configuration: <?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <buildFilters default-value="${project.build.filters}"/>
  <encoding default-value="${project.build.sourceEncoding}">${encoding}</encoding>
  <escapeString>${maven.resources.escapeString}</escapeString>
  <escapeWindowsPaths default-value="true">${maven.resources.escapeWindowsPaths}</escapeWindowsPaths>
  <includeEmptyDirs default-value="false">${maven.resources.includeEmptyDirs}</includeEmptyDirs>
  <outputDirectory default-value="${project.build.outputDirectory}"/>
  <overwrite default-value="false">${maven.resources.overwrite}</overwrite>
  <project default-value="${project}"/>
  <resources default-value="${project.resources}"/>
  <session default-value="${session}"/>
  <supportMultiLineFiltering default-value="false">${maven.resources.supportMultiLineFiltering}</supportMultiLineFiltering>
  <useBuildFilters default-value="true"/>
  <useDefaultDelimiters default-value="true"/>
</configuration>
[DEBUG] =======================================================================
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-cli) @ ztest ---
[DEBUG] Dependency collection stats: {ConflictMarker.analyzeTime=800996, ConflictMarker.markTime=442027, ConflictMarker.nodeCount=77, ConflictIdSorter.graphTime=504035, ConflictIdSorter.topsortTime=333938, ConflictIdSorter.conflictIdCount=26, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=4301939, ConflictResolver.conflictItemCount=74, DefaultDependencyCollector.collectTime=132168286, DefaultDependencyCollector.transformTime=8118047}
...
[DEBUG] -- end configuration --
[DEBUG] properties used {java.vendor=Oracle Corporation, env.SYSTEMROOT=C:\Windows, env.MOZ_PLUGIN_PATH=D:\Program Files (x86)\Foxit Software\Foxit Reader\plugins\, env.USERDOMAIN_ROAMINGPROFILE=DESKTOP-5KL2IOV, env.ORACLE_HOME=D:\e\oracle\instantclient_11_2, sun.java.launcher=SUN_STANDARD, sun.management.compiler=HotSpot 64-Bit Tiered Compilers, env.PROMPT=$P$G, env.WDIR=D:\, os.name=Windows 10, sun.boot.class.path=D:\e\Java\openjdk1.8.0_181\jre\lib\resources.jar;D:\e\Java\openjdk1.8.0_181\jre\lib\rt.jar;D:\e\Java\openjdk1.8.0_181\jre\lib\sunrsasign.jar;D:\e\Java\openjdk1.8.0_181\jre\lib\jsse.jar;D:\e\Java\openjdk1.8.0_181\jre\lib\jce.jar;D:\e\Java\openjdk1.8.0_181\jre\lib\charsets.jar;D:\e\Java\openjdk1.8.0_181\jre\lib\jfr.jar;D:\e\Java\openjdk1.8.0_181\jre\classes, env.COMPUTERNAME=DESKTOP-5KL2IOV, env.ECLIPSE_WORKSPACE=D:\workspaces\trawe\withhold_2, env.ALLUSERSPROFILE=C:\ProgramData, sun.desktop=windows, java.vm.specification.vendor=Oracle Corporation, java.runtime.version=1.8.0_181-1-redhat-b13, env.HOMEPATH=\Users\witas, project.build.sourceEncoding=UTF-8, user.name=witas, maven.build.version=Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-25T02:41:47+08:00), env.DRIVERDATA=C:\Windows\System32\Drivers\DriverData, env.PATH=D:/e/Java/openjdk1.8.0_181/bin/../jre/bin/server;D:/e/Java/openjdk1.8.0_181/bin/../jre/bin;D:/e/Java/openjdk1.8.0_181/bin/../jre/lib/amd64;C:\Program Files (x86)\Windows Resource Kits\Tools\;D:\Program Files (x86)\NetSarang\Xftp 6\;D:\Program Files (x86)\NetSarang\Xshell 6\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\Program Files\TortoiseGit\bin;D:\Program Files\TortoiseSVN\bin;D:\Program Files\Git\cmd;C:\Program Files\OpenVPN\bin;C:\Users\witas\AppData\Local\Microsoft\WindowsApps;D:\e\Java\openjdk1.8.0_181\bin;D:\e\maven\apache-maven-3.6.0\bin;D:\e\tomcat\apache-tomcat-8.0.28\bin;;D:\e\eclipse\sts-4.1.0.RELEASE;, user.language=zh, env.JVMCONFIG=\.mvn\jvm.config, env.WINDIR=C:\Windows, sun.boot.library.path=D:\e\Java\openjdk1.8.0_181\jre\bin, classworlds.conf=D:\e\maven\apache-maven-3.6.0\bin\..\bin\m2.conf, java.version=1.8.0_181-1-redhat, env.PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 142 Stepping 10, GenuineIntel, user.timezone=, env.TEMP=C:\Users\witas\AppData\Local\Temp, sun.arch.data.model=64, env.EXEC_DIR=D:\workspaces\trawe\withhold_2\ztest, java.endorsed.dirs=D:\e\Java\openjdk1.8.0_181\jre\lib\endorsed, sun.cpu.isalist=amd64, env.HOMEDRIVE=C:, sun.jnu.encoding=GBK, file.encoding.pkg=sun.io, env.SYSTEMDRIVE=C:, env.NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK, file.separator=\, java.specification.name=Java Platform API Specification, maven.conf=D:\e\maven\apache-maven-3.6.0\bin\../conf, env.JAVACMD=D:\e\Java\openjdk1.8.0_181\bin\java.exe, java.class.version=52.0, user.country=CN, java.home=D:\e\Java\openjdk1.8.0_181\jre, env.APPDATA=C:\Users\witas\AppData\Roaming, env.PUBLIC=C:\Users\Public, java.vm.info=mixed mode, env.CATALINA_HOME=D:\e\tomcat\apache-tomcat-8.0.28, env.OS=Windows_NT, os.version=10.0, path.separator=;, java.vm.version=25.181-b13, user.variant=, env.USERPROFILE=C:\Users\witas, env.JAVA_HOME=D:\e\Java\openjdk1.8.0_181, java.awt.printerjob=sun.awt.windows.WPrinterJob, env.TERM=xterm, env.TMP=C:\Users\witas\AppData\Local\Temp, env.FPS_BROWSER_USER_PROFILE_STRING=Default, env.PROGRAMFILES=C:\Program Files, sun.io.unicode.encoding=UnicodeLittle, awt.toolkit=sun.awt.windows.WToolkit, user.script=, user.home=C:\Users\witas, env.COMMONPROGRAMFILES=C:\Program Files\Common Files, env.=EXITCODE=00000000, env.SESSIONNAME=Console, java.specification.vendor=Oracle Corporation, env.TNS_ADMIN=D:\e\oracle\tnsnames, library.jansi.path=D:\e\maven\apache-maven-3.6.0\bin\..\lib\jansi-native, java.library.path=D:\e\Java\openjdk1.8.0_181\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:/e/Java/openjdk1.8.0_181/bin/../jre/bin/server;D:/e/Java/openjdk1.8.0_181/bin/../jre/bin;D:/e/Java/openjdk1.8.0_181/bin/../jre/lib/amd64;C:\Program Files (x86)\Windows Resource Kits\Tools\;D:\Program Files (x86)\NetSarang\Xftp 6\;D:\Program Files (x86)\NetSarang\Xshell 6\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\Program Files\TortoiseGit\bin;D:\Program Files\TortoiseSVN\bin;D:\Program Files\Git\cmd;C:\Program Files\OpenVPN\bin;C:\Users\witas\AppData\Local\Microsoft\WindowsApps;D:\e\Java\openjdk1.8.0_181\bin;D:\e\maven\apache-maven-3.6.0\bin;D:\e\tomcat\apache-tomcat-8.0.28\bin;;D:\e\eclipse\sts-4.1.0.RELEASE;;., env.NUMBER_OF_PROCESSORS=8, java.vendor.url=http://java.oracle.com/, env.COMMONPROGRAMFILES(X86)=C:\Program Files (x86)\Common Files, env.PSMODULEPATH=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules, env.CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher, env.MAVEN_CMD_LINE_ARGS=resources:resources -PPRO -X, java.vm.vendor=Oracle Corporation, maven.home=D:\e\maven\apache-maven-3.6.0\bin\.., java.runtime.name=OpenJDK Runtime Environment, sun.java.command=org.codehaus.plexus.classworlds.launcher.Launcher resources:resources -PPRO -X, java.class.path=D:\e\maven\apache-maven-3.6.0\bin\..\boot\plexus-classworlds-2.5.2.jar, env.PROGRAMW6432=C:\Program Files, maven.version=3.6.0, env.PROGRAMFILES(X86)=C:\Program Files (x86), java.vm.specification.name=Java Virtual Machine Specification, env.LOGONSERVER=\\DESKTOP-5KL2IOV, java.vm.specification.version=1.8, env.PROCESSOR_ARCHITECTURE=AMD64, env.COMMONPROGRAMW6432=C:\Program Files\Common Files, sun.cpu.endian=little, sun.os.patch.level=, java.io.tmpdir=C:\Users\witas\AppData\Local\Temp\, env.PROCESSOR_REVISION=8e0a, java.vendor.url.bug=http://bugreport.sun.com/bugreport/, maven.multiModuleProjectDirectory=D:\workspaces\trawe\withhold_2\ztest, env.PROGRAMDATA=C:\ProgramData, env.ECLIPSE_HOME=D:\e\eclipse\sts-4.1.0.RELEASE, env.COMSPEC=C:\Windows\system32\cmd.exe, env.FPS_BROWSER_APP_PROFILE_STRING=Internet Explorer, os.arch=amd64, java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment, java.ext.dirs=D:\e\Java\openjdk1.8.0_181\jre\lib\ext;C:\Windows\Sun\Java\lib\ext, env.=D:=D:\workspaces\trawe\withhold_2\ztest, user.dir=D:\workspaces\trawe\withhold_2\ztest, env.MAVEN_HOME=D:\e\maven\apache-maven-3.6.0\bin\.., env.LOCALAPPDATA=C:\Users\witas\AppData\Local, changethis=bbbbbbbbbbbbb, line.separator=
, env.CLASSWORLDS_JAR="D:\e\maven\apache-maven-3.6.0\bin\..\boot\plexus-classworlds-2.5.2.jar", java.vm.name=OpenJDK 64-Bit Server VM, env.PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC, env.ERROR_CODE=0, env.USERNAME=witas, sun.stderr.encoding=ms936, file.encoding=GBK, env.USERDOMAIN=DESKTOP-5KL2IOV, java.specification.version=1.8, env.PROCESSOR_LEVEL=6, env.MAVEN_PROJECTBASEDIR=D:\workspaces\trawe\withhold_2\ztest}
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[DEBUG] resource with targetPath null
directory D:\workspaces\trawe\withhold_2\ztest\src\main\resources
excludes []
includes []
[DEBUG] ignoreDelta true
[INFO] Copying 1 resource
[DEBUG] file bootstrap.yml has a filtered file extension
[DEBUG] filtering D:\workspaces\trawe\withhold_2\ztest\src\main\resources\bootstrap.yml to D:\workspaces\trawe\withhold_2\ztest\target\classes\bootstrap.yml
[DEBUG] no use filter components
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.446 s
[INFO] Finished at: 2019-09-04T17:47:54+08:00
[INFO] ------------------------------------------------------------------------

 

target\classes\bootstrap.yml 内容:

a: bbbbbbbbbbbbb

 

实际应用

 

posted on 2023-06-06 12:42  zno2  阅读(131)  评论(0编辑  收藏  举报

导航