您可以通过设置 ConfigurationSourceProvider 来实现您想要的,您可以在其中将配置设置替换为 Parameter Store 变量的值。
@Override
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
ParameterStoreSourceProvider parameterStoreSourceProvider =
new ParameterStoreSourceProvider(bootstrap.getConfigurationSourceProvider());
bootstrap.setConfigurationSourceProvider(parameterStoreSourceProvider);
}
实现一个ConfigurationSourceProvider,它接管来自委托的配置输入流以替换值。
public class ParameterStoreSourceProvider implements ConfigurationSourceProvider {
private final ConfigurationSourceProvider delegate;
private final StringSubstitutor substitutor;
public ParameterStoreSourceProvider(ConfigurationSourceProvider delegate) {
this.delegate = delegate;
this.substitutor = new StringSubstitutor(new ParameterStoreLookup());
}
@Override
public InputStream open(String path) throws IOException {
try (Scanner scanner = new Scanner(delegate.open(path))) {
String config = scanner.useDelimiter("\\A").next();
String substituted = substitutor.replace(config);
return new ByteArrayInputStream(substituted.getBytes(StandardCharsets.UTF_8));
}
}
}
在您让StringSubstitutor 使用它作为变量解析器的地方实现您的ParameterStoreLookup。
public class ParameterStoreLookup implements StringLookup {
@Override
public String lookup(String s) {
// Lookup the value from Parameter Store and return.
return null;
}
}
经过上述步骤,您可以在配置文件中定义一个变量,如下所示:
database:
driverClass : org.postgresql.Driver
url: ${DB_URL}
user: ${DB_USER}
password: ${DB_PASSWORD}
logging:
level: INFO
appenders:
- type: console
有关定义变量的更多信息,请参阅StringSubstitutor。确保将commons-text 添加到您的依赖项中。