我有以下 Spring Boot (3.3.0) config.yaml:
spring:
datasource:
appname: ${DOCUMENT_ID_DATABASE_APPNAME:DocumentIdService}
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql:characterEncoding=UTF8&rewriteBatchedStatements=true
username: ${DOCUMENT_ID_DATABASE_USERNAME:postgres}
password: ${DOCUMENT_ID_DATABASE_PASSWORD:password}
我不想从 DOCUMENT_ID_DATABASE_PASSWORD 环境变量中读取密码,而是希望由环境变量指向的文件读取密码,例如如果
DOCUMENT_ID_DATABASE_PASSWORD_FILE=/tmp/passwordfile
,那么这意味着:
password: // Set to content of /tmp/passwordfile, or if /tmp/passwordfile does not exist, default to "mypassword"
为此,您必须实现自己的环境后处理器,在其中您必须读取所需属性的值。
@Order
public class PropertiesLoader implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
// use environment to read and write properties
}
}
您必须通过在
META-INF/spring.factories
文件中指定类的全名来注册您自己的后处理器实现:
org.springframework.boot.env.EnvironmentPostProcessor=com.example.PropertiesLoader