如何读取Spring数据源URL的值,无论它在何处指定?

问题描述 投票:1回答:1

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

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

默认情况下,SpringApplication会将任何命令行选项参数(以' - '开头,例如--server.port = 9000)转换为属性并将其添加到Spring环境中。

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);

无效 无效 无效

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

java spring spring-boot
1个回答
1
投票

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

为了获得一个属性,注入Enviroment并调用Enviroment#getProperty

var property = environment.getProperty("spring.datasource.url");
© www.soinside.com 2019 - 2024. All rights reserved.