在 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);
零
零
零
如何获取数据源(特别是主机(的值,无论数据源是在属性文件中、在命令行上还是通过环境变量提供的?
有一个类org.springframework.core.env.Environment
它是 Spring 对从不同来源接收的所有属性的抽象,默认情况下包括 systemProperties
和 systemEnvironment
。
为了获得属性,注入Enviroment
并调用Enviroment#getProperty
:
var property = environment.getProperty("spring.datasource.url");