【问题标题】:Javaconfig bean overriding failing with List injectedJavaconfig bean 覆盖失败​​并注入 List
【发布时间】:2013-11-04 16:02:19
【问题描述】:

我将 bean 的注入视为自动检测到的 bean 的列表:我介绍了几个实现相同接口的 bean,并将它们全部作为一个列表注入到以后的 bean 中。

我无法找到与此功能相关的官方文档。我的单一来源是http://www.coderanch.com/t/605509/Spring/Java-config-autowired-List

考虑到这个特性,我对 Bean 覆盖有一个问题:我想用检测到的 bean 列表定义的 bean 覆盖通过无参数方法定义的 bean。但是,spring 的行为就像第二个 bean 定义不存在一样。

可以通过以下测试重现:

import java.util.Date;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class SpringTest {

    @Test
    public void shouldtestSpringDifferentMethodNames() {
        AnnotationConfigApplicationContext ctx2 = new AnnotationConfigApplicationContext(AConfig.class, CConfig.class);
        Assert.assertEquals("overriden", ctx2.getBean("bean"));
    }

    @Configuration
    public static class AConfig {

        @Bean
        public Object bean() {
            return "not overriden";
        }

    }

    @Configuration
    public static class CConfig extends AConfig {

        @Bean
        public Date anotherBean() {
            return new Date();
        }

        @Bean
        public Object bean(List<? extends Date> someDate) {
            return "overriden";
        }

    }

}

如果这是预期的行为,我该如何实现这样的覆盖?

【问题讨论】:

    标签: java spring


    【解决方案1】:
    1. 可以在 spring documentation找到列表自动装配的文档

    2. 通过 id 或名称覆盖 beans 不是 Spring 的官方功能 - 查找 question 了解更多详细信息

    【讨论】:

    • 感谢您的文档。然而,bean 的重载(而不是覆盖)似乎是一个官方特性,因为相关的 Spring 问题已被视为一个错误,并将在 3.2.5 和 4.0 中修复
    【解决方案2】:

    Spring 团队认为这是一个错误:https://jira.springsource.org/browse/SPR-10988

    最近的一篇文档可以在以下位置找到:http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-autowired-annotation(感谢 Alexander Kudrevatykh 提供 2.5 源代码)

    【讨论】:

      猜你喜欢
      • 2014-05-03
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 2013-05-08
      • 2017-08-24
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多