spring maven profile - 根据编译配置文件设置属性文件

2023-12-23

我会创建一些像这样的编译配置文件:

  • 个人资料名称:dev
  • 配置文件名称:测试
  • 配置文件名称:生产

在 src/main/resources 中我有 3 个文件夹:

  • 开发/文件.属性
  • 测试/文件.属性
  • 生产/文件.properties

每个文件包含此属性的不同值:

- my.prop.one
- my.prop.two
- my.prop.three

之后我会在 Spring 类中设置如下内容:

@Configuration
@PropertySource("file:${profile_name}/file.properties")
public class MyConfig{

}

我能怎么做?


See Apache Maven 资源插件/过滤 https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html and Maven:完整参考 - 9.3。资源过滤 https://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html. (过滤恕我直言,这是一个坏名字,因为过滤器通常会过滤一些东西out,当我们执行字符串插值这里。但事情就是这样。)

Create one file.properties in src/main/resources其中包含${...}变量值应根据您的环境而变化。

声明默认属性(用于dev)并在 POM 中激活资源过滤:

<project>
  ...
  <properties>
    <!-- dev environment properties, 
         for test and prod environment properties see <profiles> below -->
    <name>dev-value</name>
    ...
  </properties>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>
  ...

在 POM 中声明两个具有相应属性的配置文件:

  ...  
  <profiles>
    <profile>
      <id>test</id>
      <properties>
        <name>test-value</name>
        ...
      </properties>
    </profile>

    <profile>
      <id>prod</id>
      <properties>
        <name>prod-value</name>
        ...
      </properties>
    </profile>

  </profiles>
  ...

只需在您的代码中使用:

@PropertySource("file:file.properties")

通过以下方式激活配置文件:

mvn ... -P test ...

or

mvn ... -P prod ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring maven profile - 根据编译配置文件设置属性文件 的相关文章

随机推荐