如何在Spring中inheritanceapplication.properties?

如果我创建一个具有定义常见配置的application.properties的公共库。 喜欢:

spring.main.banner-mode=off

如何将这些属性inheritance到另一个包含那些公共库的项目中?

Maven的:

  de.mydomain my-core 1.0.0    my.domain my-commons 1.0.0    

如何从my-commonsinheritance配置到my-core

解决方案是使用不同的名称包含共享属性,这里是application-shared.properties

在共享库中:

 @SpringBootApplication @PropertySource(ResourceUtils.CLASSPATH_URL_PREFIX + "application-shared.properties") //can be overridden by application.properties public class SharedAutoConfiguration { } 

在主应用程序中:

 @SpringBootApplication @Import(SharedAutoConfiguration.class) public class MainAppConfiguration extends SpringBootServletInitializer { } 

这样可以加载commons / shared配置,但是可以在主app的application.properties中覆盖。

它不适用于spring.main.banner-mode属性(不知道为什么),但是对于所有其他属性,它运行良好。

你可以尝试使用Spring。

您可以在提到的公共模块中定义src/main/resources/application.properties 。 它将出现在依赖于它的其他项目的类路径中。

然后使用Annotation @PropertySource ,在依赖于公共模块的其他项目中:

 @Configuration @PropertySource("classpath*:META-INF/spring/properties/*.properties") public class Config { ... } 

或者使用XML配置:

  

它应该导入give classpath目录中的所有配置文件。

此外,您应该知道在类路径中不能有两个相同的文件。 你会发生冲突。

例如,这种情况会产生冲突

项目A(取决于项目B):

  • src/main/resources/application.properties

项目B:

  • src/main/resources/application.properties

您必须重命名application.properties文件或将其放在不同的目录中。