我有 self 配置的 Spring Cloud Config 服务器(它使用自己进行自己的配置)。
所以基本上我有一个文件 bootstrap.properties
内容:
spring.cloud.config.server.bootstrap=true
spring.cloud.config.server.git.uri=<my GitHub repo>
spring.application.name=config
spring.profiles.active=development
它运行良好,但我想使用 Java 代码定义上面的属性。事实上,我可以将这些属性保留在那里,我只是想添加 spring.cloud.config.server.git.username
和spring.cloud.config.server.git.password
以编程方式。有可能以某种方式做到这一点吗?
我尝试使用常见方法来添加/覆盖 application.properties
中定义的 Spring 属性。 ,但没有成功:看起来像 bootstrap.properties
应该以其他方式以编程方式声明(如果可能的话)。
最佳答案
好吧,在深入研究 Spring 源代码之后,我设法找到了解决方案。我不喜欢它,因为它看起来像一个肮脏的黑客,但至少它有效。如果有人提出更清洁的解决方案,我将不胜感激。
资源/META-INF/spring.factories:
# Bootstrap components
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
my.awesome.package.ConfigClientBootstrapConfiguration
ConfigClientBootstrap配置:
@Configuration
public class ConfigClientBootstrapConfiguration {
@Autowired
private ConfigurableEnvironment environment;
@Autowired
private ConfigServerProperties server;
@Bean
public MultipleJGitEnvironmentRepository environmentRepository() {
Map<String, Object> properties = new HashMap<>();
properties.put("spring.cloud.config.server.bootstrap", "true");
properties.put("spring.cloud.config.server.git.uri", "<GitHub repo URI>");
properties.put("spring.cloud.config.server.git.username", "username");
properties.put("spring.cloud.config.server.git.password", "password");
properties.put("spring.application.name", "config");
properties.put("spring.profiles.active", "development");
MapPropertySource customPropertySource = new MapPropertySource("applicationConfig: [classpath:/bootstrap.properties]", properties);
environment.getPropertySources().replace("applicationConfig: [classpath:/bootstrap.properties]", customPropertySource);
MultipleJGitEnvironmentRepository repository = new MultipleJGitEnvironmentRepository(this.environment);
if (this.server.getDefaultLabel() != null) {
repository.setDefaultLabel(this.server.getDefaultLabel());
}
return repository;
}
}
附注还可以在此处添加对现有属性的迭代,以将它们保留在文件中(并可能覆盖)。
P.P.S。我不知道为什么,但它仅适用于类名 ConfigClientBootstrapConfiguration
。当我重命名它时,它停止工作。不过我不太关心这里的命名...
关于java - Spring Cloud 配置: define server config properties programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48831700/