使用 spring-boot 在库中设置默认属性

Set default properties in a library with spring-boot

我有许多使用 spring-boot 的不同服务。我想设置一些对每个服务都通用的配置,但允许服务拥有自己的属性并在需要时覆盖它们。示例属性包括 spring.show_banner、管理 url 等

我该怎么做?如果我有以下内容:

我希望它们与优先的 service1 版本合并。相反,似乎只使用了在类路径上找到的第一个。

(或者,使用@Configuration 类 会更好,但我不确定它们是否可用于定义许多属性)

您有多种选择,全部基于 order in which property sources are considered

如果您的公共库负责创建 SpringApplication,它可以使用 setDefaultProperties。这些值可以被您的服务覆盖 application.properties.

或者,您的图书馆可以在其中一个 @Configuration 类 上使用 @PropertySource 来配置 library.properties 作为来源。同样,这些属性随后可以在您的服务 application.properties.

中被覆盖

我不确定你所说的合并它们是什么意思。

但我假设您最终描述的是您具有特定于配置文件的配置的情况。因为,特定服务的任何属性都可以 managed/injected 使用 Spring 配置文件, 将始终优先于默认 属性 文件(见 documentation).

例如,您可以拥有文件 application-service1.properties,当您 运行 您的应用带有 属性 spring.profiles.active=service1 时,该文件将自动使用,可以在命令行和 other places。 如果您不指定此 属性,Spring 引导将回退到默认的 application.properties 文件。

你当然可以在两个文件中写共同的属性:

application.properties:

service.url=http://localhost:8080/endpoint
service.user=admin
service.password=admin

申请-service1.properties:

service.url=http://api.service.com/endpoint
service.user=admin
service.password=aosdnoni3
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            ApplicationEnvironmentPreparedEvent envEvent = (ApplicationEnvironmentPreparedEvent) event;
            ConfigurableEnvironment env = envEvent.getEnvironment();
            Properties props = new Properties();
            //set props as desired
            env.getPropertySources()
                    .addFirst(new PropertiesPropertySource("customname", props));
    }
}

然后在src/main/resources/META-INF/spring.factories中,添加一行: org.springframework.context.ApplicationListener=mypackage.MyApplicationListener