Spring Bean引用失效:无法访问Sample Bean的modified属性
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,
urlis stillnull. - If
baseUrlin your code is a typo forurl, callingurl.equals("")will throw aNullPointerException(you can't invoke methods on anullvalue). Even if you're checking for an empty string correctly, theRuntimeExceptionwill trigger, causing theSamplebean to fail initialization entirely. This means when Spring tries to resolve#{sample.modified}, there's no validsamplebean 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.
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

