Spring无法为List类型的bean解析@Bean依赖项?

eis*_*eis 4 java spring

简单的测试类显示我的问题:

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringTest.OptionalConfiguration.class)
public class SpringTest {
    static class Item extends Object {}

    @Configuration
    static class OptionalConfiguration {
        @Bean
        List<Item> someString() {
            return new ArrayList<>();
        }
        @Bean
        Object foo(List<Item> obj) {
            return new Object();
        }
    }

    @Test
    public void testThis() {

    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖[SpringTest $ Item的集合]找到[SpringTest $ Item]类型的限定bean:预期至少有一个bean可以作为此依赖项的autowire候选者.依赖注释:{}

如果我从改变List<Item>Item,工作的事情.

这是设计的吗?任何解决方法?我需要提供一些List项目 - 有时是空的,有时是项目,具体取决于运行时配置.

我知道如果我指定类型为Item的bean,则自动装配List<Item>有效.但是,我想要一个类型的bean List<Item>(或者如果我不能拥有它,那么List).

使用Spring 4.2.4.

Sot*_*lis 8

该片段在Spring 4.3+中可以正常使用.该文档的状态

也就是说,从4.3开始,只要元素类型信息保留在返回类型签名或集合继承层次结构中,集合/映射和数组类型也可以通过Spring的@Autowired类型匹配算法[也用于@Bean参数解析]进行匹配.@Bean.在这种情况下,限定符值可用于在相同类型的集合中进行选择,如上一段所述.

在春天看到的4.3之前

@Bean
Object foo(List<Item> obj) {
Run Code Online (Sandbox Code Playgroud)

它试图List动态创建一个对象,包含在中Item找到的所有bean ApplicationContext.你ApplicationContext不包含任何东西,所以Spring报告错误.

以下是一些解决方法.这个

@Bean
Object foo() {
    List<Item> someString = someString();
    return new Object();
}
Run Code Online (Sandbox Code Playgroud)

直接使用缓存的bean工厂方法someString.

这个

@Resource(name = "someString")
private List<Item> items;
// and access 'items' wherever you need it in the configuration 
Run Code Online (Sandbox Code Playgroud)

因为

如果您打算按名称表达注释驱动的注入,请不要主要使用@Autowired,即使技术上能够通过@Qualifier值引用bean名称.相反,使用JSR-250 @Resource注释,该注释在语义上定义为通过其唯一名称标识特定目标组件,声明的类型与匹配过程无关.@Autowired具有相当不同的语义:在按类型选择候选bean之后,指定的字符串限定符值将仅在那些类型选择的候选中被考虑,例如,将"帐户"限定符与标记有相同限定符标签的bean匹配.