【发布时间】:2020-06-21 05:05:47
【问题描述】:
我正在编写自定义 Spring Boot 启动项目,其中我们有自己的类 VaultFactory,它根据 application.yml 文件中定义的消费者属性连接到保险库。
在自定义启动项目中,我可以读取所有秘密和相应的值。现在,我想将所有这些键/值对公开为属性源,以便消费者可以通过@value 直接访问
@Value{${some.vault.secret.name}}
private String value;
我的入门项目代码
@Configuration
@EnableConfigurationProperties(VaultConfiguration.class)
@ConditionalOnClass(VaultFactory.class)
public class VaultEnableAutoConfiguration {
/**
* @param vaultConfiguration
* @return
* @throws VaultException
*/
@Bean
@ConditionalOnMissingBean
public Vault getVaultFactoryByProperties(VaultConfiguration vaultConfiguration) throws VaultException {
VaultFactory vaultFactory = VaultFactory.newInstance(vaultConfiguration.getVault().get("file.path"), vaultConfiguration.getVaultProperties());
return vaultFactory.getVault("vault-01");
}
}
@EnableConfigurationProperties(VaultConfiguration.class)
public class VaultPropertiesConfiguration {
@Autowired
Vault vault;
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(VaultConfiguration vaultConfiguration) throws VaultException {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources ps = environment.getPropertySources();
pspc.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
pspc.setIgnoreUnresolvablePlaceholders(true);
ps.addLast(new VaultPropertySource("vaultProperties", vault));
pspc.setPropertySources(ps);
return pspc;
}
}
public class VaultPropertySource extends PropertySource<Vault>{
Vault vault;
public VaultPropertySource(String name) {
super(name);
}
public VaultPropertySource(String name, Vault vault) {
super(name);
this.vault = vault;
}
@Override
public Object getProperty(String name) {
try {
return vault.getSecret(name).getValue();
} catch (VaultException e) {
e.printStackTrace();
}
return null;
}
}
@ConfigurationProperties("platform")
public class VaultConfiguration {
private final Map<String, String> vault = new HashMap<>();
public Map<String, String> getVault() {
return vault;
}
public Properties getVaultProperties() {
Properties p = new Properties();
vault.entrySet().stream().forEach( e -> p.put(e.getKey(), e.getValue()));
return p;
}
}
我该怎么做?基本上,如果我的启动项目中有一个键/值映射,我如何通过@value 注释使这些可用于启动应用程序?
面临多个问题:
VaultPropertiesConfiguration 总是首先被调用,而@EnableConfigurationProperties 和@autowired 不起作用。
我进行了硬编码以解决上述问题,但它正在尝试从我没有的 propertysource 加载 spring.messages.always-use-message-format 属性。
【问题讨论】:
-
只需在环境中注册一个新的
PropertySource或为您的案例创建一个专用的PropertySource(就像 Spirng Cloud Config 一样)并注册。 -
@M.Deinum 我尝试在我的自定义启动项目中添加属性源,但我遇到了一些问题。你能告诉我我做错了什么吗?
标签: spring spring-boot properties spring-boot-starter