在Spring Boot文档中,它声明命令行上以--
开头的值将转换为系统属性。
默认情况下,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");