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

Spring 4.3.15中context.xml配置ClassUtils Bean时出现BeanCreationException

问题根源与修复方案

嘿,这个问题我之前帮人排查过,本质是Spring版本升级后的API签名不兼容导致的NoSuchMethodError,我给你拆解下原因和解决办法:

为什么会报错?

你之前在Spring 3.2.18里用的org.springframework.util.ClassUtils.forName(String)方法,到了Spring 4.3.15版本已经被修改了——4.3.x版本移除了无ClassLoader参数的forName重载,只保留了forName(String, ClassLoader)这个签名。你的旧配置还是调用原来的单参数方法,自然会找不到对应的方法,进而抛出BeanCreationException。


修复方案1:修改XML配置适配新方法签名

既然Spring 4.3要求传入类加载器参数,我们可以给MethodInvokingFactoryBean添加arguments属性,指定类名和类加载器:

<bean id="id1" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass" value="org.springframework.util.ClassUtils"/>
    <property name="targetMethod" value="forName"/>
    <!-- 传入两个参数:你要加载的全类名 + 当前线程的上下文类加载器 -->
    <property name="arguments">
        <list>
            <value>com.example.YourTargetClass</value>
            <bean class="java.lang.Thread" factory-method="currentThread">
                <property name="contextClassLoader"/>
            </bean>
        </list>
    </property>
</bean>

或者用SpEL表达式更简洁地获取BeanFactory的类加载器:

<property name="arguments">
    <list>
        <value>com.example.YourTargetClass</value>
        <value>#{beanFactory.beanClassLoader}</value>
    </list>
</property>

修复方案2:改用Java配置(更推荐)

如果你的项目允许切换到Java配置,这种方式会更清晰,也能避免XML配置里的方法签名问题:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;

@Configuration
public class YourConfig {

    @Bean
    public Class<?> id1() throws ClassNotFoundException {
        // 传入类名和当前类的类加载器
        return ClassUtils.forName("com.example.YourTargetClass", getClass().getClassLoader());
    }
}

额外提醒

  • 升级Spring版本时,一定要留意官方的版本迁移文档,重点关注废弃API和方法签名变更,避免踩这类兼容性坑。
  • 确保项目中所有Spring相关依赖的版本保持一致,混合不同版本的Spring JAR包很容易引发类加载或API兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:24:20