美文网首页
spring中使用maven环境参数

spring中使用maven环境参数

作者: fzhyzamt | 来源:发表于2021-09-28 10:56 被阅读0次

资源文件默认使用${...}为占位符,但如果pom继承了 spring-boot-starter-parent,那么默认占位符就改为了 @...@
例如:

#application.yml
spring:
  profiles:
      active: @profiles.active@
# pom.xml
<project>
...
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/>
    </parent>
    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <profiles.active>dev</profiles.active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <profiles.active>prod</profiles.active>
            </properties>
        </profile>
    </profiles>
    <build>
        <finalName>Example</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <excludes>
                    <exclude>application*.yml</exclude>
                    <exclude>config/**</exclude>
                </excludes>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>application.yml</include>
                    <include>application-${profiles.active}.yml</include>
                    <include>config/${profiles.active}/*</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

另外注意一点,Intellij IDEA运行Springboot项目时,默认会使用内置的编译器,不去执行maven中的编译配置。这将导致maven build正常,但run/debug报错,报错信息如下:

org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
 in 'reader', line 11, column 15:
          active: @profiles.active@
                  ^

这个问题可以通过启用IDEA的Delegate IDE build/run actions to Maven来解决。这个选项为项目级设置,启用后每次编译时将不再使用内置编译,而是调用maven。官方选项说明

image.png

spring-boot-help
Apache占位符文档

相关文章

网友评论

      本文标题:spring中使用maven环境参数

      本文链接:https://www.haomeiwen.com/subject/ccwlnltx.html