【问题标题】:Spring loading beans which are based on application.properties from a sub-module基于子模块的 application.properties 的 Spring 加载 bean
【发布时间】:2015-08-30 18:21:23
【问题描述】:

我有两个 Spring 模块,父模块有一个子模块依赖项。这两个项目都有自己的带有 Spring 注释的 bean,并且 bean 是使用 @Bean 创建的。 项目子的资源中有child.properties,该文件用于为子项目中的Bean 设置属性。 Project Parent 有自己的parent.properties,它也用于在父项目中创建 bean。

=> 每两个项目的ServiceConfig 类都用@Configuration 注释,我使用它:

家长:

@Bean public static PropertyPlaceholderConfigurer configuration(){
        final PropertyPlaceholderConfigurer props=new PropertyPlaceholderConfigurer();
        props.setLocations(new Resource[]{new ClassPathResource("parent.properties")});
        return props;
    }

孩子:

@Bean public static PropertyPlaceholderConfigurer configuration(){
        final PropertyPlaceholderConfigurer props=new PropertyPlaceholderConfigurer();
        props.setLocations(new Resource[]{new ClassPathResource("child.properties")});
        return props;
    }

现在我的问题是:我需要将 bean 从子项目自动装配到父项目,当我运行父项目(在 pom.xml 中有子项目作为依赖项)时,无法构造自动装配的子 bean,因为child.properties 未加载。当我调试时,我看到 spring 只从父级而不是子级进入 PropertyPlaceholderConfigurer bean。 当我从父项目中删除 PropertyPlaceholderConfigurer 时,Spring 会从子项目中加载 PropertyPlaceholderConfigurer Bean。

我可以通过将child.properties 文件放在父项目中来解决此问题,但我不喜欢此解决方案,我想按项目保留每个配置。

【问题讨论】:

  • 尝试将子子模块中的方法“configuration”重命名为“childConfiguration”,看看是否有帮助。

标签: java spring


【解决方案1】:

由于两个 PropertyPlaceholderConfigurer bean 的 bean 名称相同,因此子 bean 被父 bean 覆盖(如果您仔细查看日志,您会看到它在那里声明) 试着给他们起不同的名字

【讨论】:

    【解决方案2】:

    使用 @PropertySources 注释来注释相应应用程序的 Spring 配置。它允许您指定 @PropertySource 文件的数组。

    例如

    @Configuration
    @PropertySources({
        @PropertySource("classpath:parent.properties"),
        @PropertySource("classpath:child.properties")})
    public class MyApp() // Add annotations on YOUR configuration 
    {
        ...
    }
    

    Spring 会将注解的属性添加到您的应用程序中。有关更多信息,请查看 spring 文档中的 chapter 23

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 2019-04-17
      • 2015-01-03
      • 2016-03-04
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      相关资源
      最近更新 更多