如何在Spring Boot中将环境变量与application.properties一起使用?

问题描述 投票:0回答:2

我正在尝试配置我的 application.properties 以从我设置的系统变量中获取值。问题是无论我做什么都行不通。我尝试使用来自此示例的数据源的自定义类配置仍然没有成功。我在 stackoverflow 上找到的只是指向 official docs 的链接。 不幸的是,这是一个死胡同,因为它没有说什么,也没有我想要实现的目标的示例。我还发现了像

spring.datasource.url = ${SPRING_DATASOURCE_URL}
这样的例子,每个人都在说spring会知道如何自动获取环境变量。令人惊讶的是,事实并非如此。

我还发现了像

spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD:the_actual_password)
spring.datasource.url = #{SPRING_DATASOURCE_URL:#{'the_actual_url'}}
这样的例子,这完全不是我需要的,如果你问我的话,它是毫无用处的。我的意思是我可以通过写作实现同样的目标
spring.datasource.password = the_actual_password
。重点是隐藏敏感数据..

现在,话虽这么说,我将留下 2 张我所拥有的屏幕截图。我之所以试图实现这一目标,是因为当我推送到 GitHub 时,我不必担心我的凭据或任何内容会公开给每个人看。

这是我的环境变量的样子:

这是 application.properties 的样子:

提前谢谢您!如果您对我的问题有答案,您能否也让我知道如何使用环境变量实现相同的目标,但对于 application.jwt 属性?

java spring-boot spring-data-jpa jwt environment-variables
2个回答
3
投票

它不起作用的原因是因为环境变量是在 IntelliJ 首次打开后定义的,如此处所述。现在看来一切都正常。

我成功实现了我想要的功能。

换句话说:

spring.datasource.url = ${SPRING_DATASOURCE_URL}
spring.datasource.username = ${SPRING_DATASOURCE_USERNAME}
spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD}
spring.datasource.driver-class-name = ${SPRING_DATASOURCE_DRIVERCLASSNAME}

现在工作完美。


-1
投票

您使用了正确的注释吗?

给定属性如下:

root.test = ${TEST.VAR:-Test}

环境变量如:

TEST.VAR = Something

配置类:

@Configuration
@ConfigurationProperties(prefix = "root")
public class Test {
  private String test;

  public String getTest() {
    return test;
  }

  public void setTest(String test) {
    this.test = test;
  }

}

您可以通过在主类上设置

Records
来使用
@ConfigurationPropertiesScan

@SpringBootApplication
@ConfigurationPropertiesScan
public class DemoApplication{...}

像这样定义记录:

@ConfigurationProperties(prefix = "root")
public record Test (String test) {
}
© www.soinside.com 2019 - 2024. All rights reserved.