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

使用BeanFactory.getBean调用带类型参数的Spring @Bean报错如何解决

问题原因

你调用的context.getBean("m", String.class)匹配到的是getBean(String name, Class<T> requiredType)重载方法,该方法的第二个参数是指定期望返回的Bean的类型,并非传递给@Bean工厂方法的入参。Spring会尝试查找名称为m、类型为String的Bean,自然就抛出了类型不匹配的异常。

解决方案

针对prototype作用域的Bean,Spring提供了支持传入构造/工厂方法参数的getBean重载,你可以选择以下任意一种写法调用:

ConfigurableApplicationContext context = SpringApplication.run(Demo2Application.class, args);           
// 方式1:指定Bean名称、返回类型,同时传入工厂方法参数,无需强制类型转换
Mother m3 = context.getBean("m", Mother.class, String.class);

// 方式2:仅指定返回Bean类型+传入参,适合该类型仅声明了一个Bean的场景
Mother m3 = context.getBean(Mother.class, String.class);

调用时传入的额外参数会被Spring直接传递给对应的@Bean方法作为入参,就能正确创建Mother实例了。

补充说明

如果你的@Bean方法入参是Spring容器中已存在的Bean,可以不用手动传参,Spring会自动完成注入。你当前场景下入参是Class<String>类型,容器中默认没有对应类型的Bean,因此需要手动传入参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:57:03