You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何注入自定义Foo类型Bean列表而非全部Bean?

解决Spring注入自定义Foo列表而非全部Foo类型Bean的问题

问题根源:Spring默认会自动将所有类型匹配Foo的Bean收集为List<Foo>注入,所以你直接声明List<Foo> defaultFoos参数时,拿到的是所有BarA/BarB/BarC的集合,而非你通过getDefaultFoos()定义的自定义列表Bean。

下面是两种可行的解决方式:

方式一:使用@Qualifier指定目标Bean

给other()方法的List<Foo>参数加上@Qualifier注解,明确指定要注入的是getDefaultFoos()生成的Bean(默认Bean名称为方法名getDefaultFoos):

class MyConfig{
    // 省略barA/barB/barC的Bean定义
    
    @Bean
    public List<Foo> getDefaultFoos(BarA barA, BarB barB) {
        return List.of(barA, barB);
    }

    @Bean
    public OtherType other(@Qualifier("getDefaultFoos") List<Foo> defaultFoos, ApplicationContext applicationContext) {
        return new OtherType(defaultFoos, applicationContext); 
    }
}

如果想让Bean名称更直观,可以给getDefaultFoos()的@Bean注解指定名称,再配合@Qualifier使用:

@Bean(name = "defaultFoos")
public List<Foo> getDefaultFoos(BarA barA, BarB barB) {
    return List.of(barA, barB);
}

@Bean
public OtherType other(@Qualifier("defaultFoos") List<Foo> defaultFoos, ApplicationContext applicationContext) {
    return new OtherType(defaultFoos, applicationContext); 
}

方式二:直接调用配置类内的Bean方法

在@Configuration类中,直接调用getDefaultFoos()方法,Spring会自动处理为获取对应的Bean实例(不会重复创建新对象):

class MyConfig{
    // 省略barA/barB/barC的Bean定义
    
    @Bean
    public List<Foo> getDefaultFoos(BarA barA, BarB barB) {
        return List.of(barA, barB);
    }

    @Bean
    public OtherType other(ApplicationContext applicationContext) {
        return new OtherType(getDefaultFoos(barA(), barB()), applicationContext); 
    }
}

注意:这里调用barA()和barB()时,Spring也会返回已创建的Bean实例,而非新实例化对象,符合Spring的Bean管理机制。


内容的提问来源于stack exchange,提问作者Prem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:36:29