java - Spring Cloud 配置: define server config properties programmatically

标签 java spring spring-cloud spring-cloud-config

我有 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.usernamespring.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/

相关文章:

java - Spring Eureka 服务器在客户端 url 中找不到上下文路径

java - 如何更改 2d ArrayList 中某些 ArrayList 的大小?

java - 关于 JButton 和 ImageIcon

java - Java转储中retained size=0是什么意思?

java - Cloud Config Server 不会解密值

java - 使用 @RefreshScope 刷新 Bean,无需更改配置

javascript - 将 JSON 字符串加载到 highcharts 中的饼图中

java - thymeleaf , Spring : stuck on creating a single item view

java - 在 Spring 中添加管理部分

java - Spring 属性未加载