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

Spring Bean引用失效:无法访问Sample Bean的modified属性

Why You're Seeing "Field or property 'sample' cannot be found" Error

Let's break down the root causes of this issue step by step:

1. @Value Injection Happens After Constructor Execution

Your Sample class tries to use the url field (injected via @Value) directly in its constructor—but Spring doesn't inject @Value fields until after the bean is instantiated with the constructor.

This creates two critical problems:

  • When your constructor runs, url is still null.
  • If baseUrl in your code is a typo for url, calling url.equals("") will throw a NullPointerException (you can't invoke methods on a null value). Even if you're checking for an empty string correctly, the RuntimeException will trigger, causing the Sample bean to fail initialization entirely. This means when Spring tries to resolve #{sample.modified}, there's no valid sample bean to reference.

2. Bean Initialization Order Is Uncontrolled

Even if the Sample bean initialized correctly, Spring doesn't guarantee the order of bean creation by default. If Spring tries to create your url String bean before the sample bean, the SpEL expression #{sample.modified} won't be able to locate the sample bean yet—leading directly to the error you're seeing.


Fixes to Resolve the Issue

Fix 1: Move Initialization Logic to @PostConstruct

Use Spring's @PostConstruct annotation to run your setup code after all dependencies (like @Value fields) are injected. This ensures url is available when you need it:

package com.test;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Sample {
    String modified = null;
    @Value("${url}")
    private String url;

    public Sample() {
        // Constructor only instantiates the bean—avoid using injected fields here
        System.out.println("Sample bean created, url not yet injected: " + url);
    }

    @PostConstruct
    public void init() {
        // Now url is properly injected
        System.out.println("PostConstruct: url value is " + url);
        
        if (url == null || url.trim().isEmpty()) {
            throw new RuntimeException("url property is missing or empty");
        }
        modified = "test" + url;
    }
}

Fix 2: Enforce Bean Initialization Order

Ensure the sample bean is fully initialized before your url String bean by adding the depends-on attribute to the url bean definition. This tells Spring to prioritize creating sample first:

<bean id="url" class="java.lang.String" depends-on="sample">
    <constructor-arg value="#{sample.modified}" />
</bean>

内容的提问来源于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:31:06