【问题标题】:Spring Boot Inherit application.properties from dependencySpring Boot 从依赖项继承 application.properties
【发布时间】:2016-06-10 08:59:31
【问题描述】:

假设我有 5 个 Spring Boot 项目。它们都对带有一些共享/公共类的 Spring Boot 项目 No 6 具有 Maven 依赖关系。 5 个独立的项目在每个 application.properties 中分配了很多公共属性,我想将它们抽象出来并将它们移动到公共项目中。总体来说是这样的:

                                            Project 1 (app.properties)
Common Project (app-common.properties) <--- Project 2 (app.properties)
                                            Project 3 (app.properties)...

当前的问题是 app-common.properties 位于 project1.jar/lib/common-project.jar 中,而 app-common.properties 显然不会在启动时加载。

有没有办法从依赖中扩展它?

CommonProject 主类如下所示:

@SpringBootApplication
public class CommonApplication extends SpringBootServletInitializer {

    protected static void run(SpringApplication application, String[] args) {
        application.run(args);
    }
}

Project1 主类如下所示:

public class Project1 extends CommonApplication {

    public static void main(String[] args) {
        run(new SpringApplication(Project1.class), args);
    }
}

【问题讨论】:

  • 并非如此。我最终将所有常见值/属性提取到带有常量的 java 类中,其中值是通过 setter 进行的 @Inject 。并且该 java 类用于底层项目。蹩脚,但快速的解决方法。如果以后找到更好的方法,我会在这里发布。
  • 谢谢,所以我实际上尝试了 Anton 下面的内容,并且成功了。我在依赖项中有一个通用的道具文件,并且使用类路径道具看起来效果很好。只需将注释放在您声明 @SpringBootApplication 的位置
  • 感谢您的输入!根据您的成功经验,我会接受安东的回答。
  • 如何在依赖中使用profiles?

标签: spring spring-boot


【解决方案1】:

使用 PropertySource 注解并为您的应用提供两个来源:

@PropertySources({
        @PropertySource("classpath:app-common.properties"),
        @PropertySource("classpath:app.properties")
    })

更多细节可以在这里找到 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

【讨论】:

【解决方案2】:

目前 spring boot 不提供继承属性。

Spring Boot 应用程序支持多个属性源,但xxx.properties 的约定(读取:内置逻辑)是如果有多个具有相同文件名的属性文件,则解析最后一个xxx.properties

有很多解决方案。

一种可能的解决方案是

  1. 将自定义配置文件应用于依赖项
  2. application-customprofile.properties 中包含可继承的设置
  3. application[-{profile}].properties 中设置依赖spring.profiles.include=customprofile(注意:如果设置在application.properties 中,则适用于所有配置文件)

另一种可能的解决方案是为属性使用唯一的自定义文件名。

  • 即不要使用默认的application.properties,而是使用common.properties

【讨论】:

猜你喜欢
  • 2022-12-22
  • 2020-07-08
  • 2017-06-18
  • 2015-12-20
  • 2017-10-20
  • 2018-05-01
  • 2020-02-28
  • 2020-11-28
  • 2015-08-02
相关资源
最近更新 更多