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

如何在Spring的@Value注解中访问另一个字段的值?

问题解决:Spring @Value访问当前Bean字段值报错

你遇到的BeanExpressionException是因为SpEL表达式里的#id并不是指向当前Bean的id字段,而是试图查找Spring上下文中名为id的Bean,找不到就会触发表达式解析失败的异常。

下面给你两种可行的解决方法:

方法一:构造注入时直接初始化(推荐)

既然id是final字段,会通过构造方法注入,那直接在构造方法里调用otherBean的方法生成idObject即可,这种方式更简洁也更符合Spring的最佳实践,完全不需要用@Value:

public class MyBean {
    private final String id;
    private final SomeObject idObject;

    // 构造方法注入id和otherBean
    public MyBean(String id, OtherBean otherBean) {
        this.id = id;
        this.idObject = otherBean.resolve(id);
    }
}

方法二:修改SpEL表达式引用当前Bean字段

如果一定要用@Value,可以在表达式里用this.id来指向当前Bean的id字段。注意当前Bean需要被Spring管理(比如标注@Component),并且确保id字段在@Value注入前已经被初始化(你这里id是final,构造注入就能满足):

@Component
public class MyBean {
    private final String id;

    @Value("#{otherBean.resolve(this.id)}")
    private SomeObject idObject;

    public MyBean(String id) {
        this.id = id;
    }

    @Autowired
    private OtherBean otherBean;
}

如果id是私有字段出现权限问题,给id加个getId() getter方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:32:41