Spring bean 引用不工作

Spring bean reference not working

我有以下 bean:

  package com.test;
  @Component
  public class Sample{

      String modified = null;

      @Value("${url}")
      private String url;

      public Sample(){
       System.out.println(url );
        if(baseUrl.equals(""){
            throw new RuntimeException("missing");
         }
        else{
           modified = "test"+url;
        }
      }
    }

我已添加:

<context:annotation-config />
    <context:property-placeholder location="classpath:test.properties"/> &    <context:component-scan base-package="com.test"/> 

并尝试访问上面的 "modified" 字段,如下所示

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

在我的应用程序上下文中。但我不断收到以下错误:

Field or property 'sample' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'

不确定为什么会出现此错误?

当Spring 创建对象时,它使用默认构造函数。在构建 属性 之前,它无法设置它。而不是你拥有的,试试这个看看是否正在设置值。

  @PostConstruct
  public void init(){
   System.out.println(url );
    if(baseUrl.equals(""){
        throw new RuntimeException("missing");
     }
  }

JustinKSU 的回答是正确的。您还有另一种选择:使用 @Autowired:

通过构造函数注入值
@Component
public class Sample {

  @Autowired
  public Sample(@Value("${url}") String url) {
    System.out.println(url);
    if(url.equals("") {
      throw new RuntimeException("missing");
    }
  }

}