gpt4 book ai didi

java - 无论 Spring 数据源 URL 是在哪里指定的,如何读取它的值?

转载 作者:行者123 更新时间:2023-11-30 05:47:57 30 4
gpt4 key购买 nike

在 Spring Boot 文档中,它指出命令行上提供的以 -- 开头的值将转换为系统属性。

https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-external-config-command-line-args

By default SpringApplication will convert any command line option arguments (starting with ‘--’, e.g. --server.port=9000) to a property and add it to the Spring Environment.

mvn spring-boot:run -Drun.arguments="-task report:weekly,--spring.datasource.url=jdbc:mysql://xx.xx.us-east-1.rds.amazonaws.com:3306/xx"

我发现这不是真的。我尝试打印数据源值,所有三个都返回 null

    System.out.println(System.getenv("SPRING_DATASOURCE_URL"));
System.out.println(System.getProperty("SPRING_DATASOURCE_URL"));
System.out.println(System.getProperty("spring.datasource.url"));
System.exit(1);

null
null
null

如何获取数据源的值,特别是主机的值,无论数据源是在属性文件中、在命令行上还是通过环境变量提供?

最佳答案

有一个类org.springframework.core.env.Environment这是 Spring 对从不同来源接收的所有属性的抽象,默认情况下包括 systemPropertiessystemEnvironment .

为了获取属性,请注入(inject)Enviroment并调用Enviroment#getProperty :

var property = environment.getProperty("spring.datasource.url");

关于java - 无论 Spring 数据源 URL 是在哪里指定的,如何读取它的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524863/

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