gpt4 book ai didi

spring - 在 Spring Boot 的 application.properties 中使用 Maven 属性

转载 作者:IT老高 更新时间:2023-10-28 13:48:24 32 4
gpt4 key购买 nike

我正在尝试将 pom.xml 中的属性加载到 application.properties。我想创建两个配置文件:dev 和 prod 以使用不同的数据库 url。我使用 Jenkins 作为 CI,在我的所有应用程序(主要是 Spring MVC,没有 Boot 项目)中都使用 maven 配置文件部署到 Tomcat。使用 maven 属性可以做到这一点吗?我尝试过这样的事情:spring.datasource.url=${jdbc.url}

最佳答案

在您执行此操作之前,请考虑将属性文件从您的可部署包中外部化。这样,您可以在每个环境中部署相同的编译。它将为您的 Jenkins 节省一些实际上不必要的工作。最佳做法是只构建您的应用程序一次,但是,如果您不相信,这里是如何做到的。

  1. 在您的 pom.xml 中使用适当的属性值定义配置文件。

    <profile>
    <id>dev</id>
    <properties>
    <jdbc.url>your_dev_URL</jdbc.url>
    </properties>
    </profile>
  2. 设置Maven Resources Plugin过滤包含您的 application.properties 文件的目录。

    <build>
    <resources>
    <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
    </resource>
    </resources>
    ...
    </build>
  3. 如果你使用 Spring Boot 1.3 或更高版本,你应该知道为了避免 Spring Boot 占位符和 Maven 资源插件过滤的 token 之间的冲突,框架引入了 a solution that requires using a different syntax过滤值。

    现在,您应该使用 @property.key@ 而不是 ${property.key}。在这种情况下,您的 application.properties 必须包含以下示例才能按预期工作:

    spring.datasource.url=@jdbc.url@

您也可以查看有关 separating Spring properties files for different Maven profiles 的帖子.这样您就可以将 pom.xml 中的值外部化。

关于spring - 在 Spring Boot 的 application.properties 中使用 Maven 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703499/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com