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

Spring MVC中Bean间传递返回值报错,咨询写法正确性

Spring EL调用Bean方法报错的问题分析

先看你遇到的具体场景:

你定义了一个Spring组件类:

package com.test; 
@Component 
public class Sample{ 
    @Value("${url}") 
    private String url = null; 
    public String getURL(){ 
        return "test"+url; 
    } 
}

然后在context.xml里配置了另一个Bean,试图调用Sample的方法来赋值:

<bean id="build" class="com.test.Consumer">
    <property name="url" value="#{new com.test.Sample().getURL()}"/>
</bean>

结果运行时抛出了错误:

java.lang.IllegalStateException: Failed to load ApplicationContext Expression parsing failed; nested exception is java.lang.NullPointerException

首先明确说:你写的value="#{new com.test.Sample().getURL()}"这种写法完全不正确,这就是触发空指针异常的核心原因。

为什么会报错?

你手动new com.test.Sample()出来的对象,根本不是Spring容器管理的Bean!Spring的@Value注解只有在容器实例化Bean的过程中才会生效,手动new的对象不会触发Spring的依赖注入流程,所以你的url字段一直是null,调用getURL()的时候拼接"test"+url自然就抛出空指针了。

正确的写法应该是怎样的?

你已经用@Component把Sample注册到Spring容器里了,容器会自动管理这个Bean的实例,你只需要在EL表达式里直接引用容器中的Sample Bean即可:

<bean id="build" class="com.test.Consumer">
    <property name="url" value="#{sample.getURL()}"/>
</bean>

这里的sample是Spring给@Component类默认生成的Bean名称(类名首字母小写),如果你给Sample指定了自定义的Bean名称(比如@Component("mySample")),那就用#{mySample.getURL()}。

另外还要确保你的组件扫描配置是正确的,Spring能扫描到com.test包下的@Component类,不然容器里也不会有Sample的实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:02:39