在application.properties你可以定义 property server.port=8081
。
spring-cloud-starter-aws-parameter-store-config支持的参数格式有:
/config/application/server.port
/config/application_dev/server.port
/config/my-service/server.port
/config/my-service_dev/server.port
通过在bootstrap.properties中定义以下属性,您可以以某种方式更改格式:
spring.application.name=my-service
aws.paramstore.prefix=/config
aws.paramstore.defaultContext=application
aws.paramstore.profileSeparator=_
但仅支持简单的自定义,因为主要参数命名逻辑是硬编码在AwsParamStorePropertySourceLocator
.
要显着改变参数格式,您必须定义一个自定义PropertySourceLocator
并将其注册为引导配置。
问题是dev.application.server.port
参数名称无效。
AWS Systems Manager Parameter Store/
用作路径分隔符,Spring 使用操作get-parameters-by-path。一种解决方法是使用 name dev.application/server.port
。
但这个名字也是无效的。参数名称必须是完全限定名称,因此有效名称是/dev.application/server.port
.
为了支持这种参数格式,定义一个自定义PropertySourceLocator
@Configuration
public class CustomAwsParamStorePropertySourceLocator implements PropertySourceLocator {
private static final Logger LOGGER =
LoggerFactory.getLogger(CustomAwsParamStorePropertySourceLocator.class);
private AWSSimpleSystemsManagement ssmClient;
private List<String> contexts = new ArrayList<>();
public CustomAwsParamStorePropertySourceLocator(AWSSimpleSystemsManagement ssmClient) {
this.ssmClient = ssmClient;
}
public List<String> getContexts() {
return contexts;
}
@Override
public PropertySource<?> locate(Environment environment) {
if (!(environment instanceof ConfigurableEnvironment)) {
return null;
}
ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
List<String> profiles = Arrays.asList(env.getActiveProfiles());
String defaultAppName = "application";
this.contexts.add("/" + defaultAppName + "/");
addProfiles(this.contexts, defaultAppName, profiles);
String appName = env.getProperty("spring.application.name");
this.contexts.add("/" + appName + "/");
addProfiles(this.contexts, appName, profiles);
Collections.reverse(this.contexts);
CompositePropertySource composite = new CompositePropertySource("custom-aws-param-store");
for (String propertySourceContext : this.contexts) {
try {
composite.addPropertySource(create(propertySourceContext));
} catch (Exception e) {
LOGGER.warn("Unable to load AWS config from " + propertySourceContext, e);
}
}
return composite;
}
private void addProfiles(List<String> contexts, String appName, List<String> profiles) {
for (String profile : profiles) {
contexts.add("/" + profile + "." + appName + "/");
}
}
private AwsParamStorePropertySource create(String context) {
AwsParamStorePropertySource propertySource =
new AwsParamStorePropertySource(context, this.ssmClient);
propertySource.init();
return propertySource;
}
}
并通过添加文件在引导上下文中注册它META-INF/spring.factories
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.example.CustomAwsParamStorePropertySourceLocator