繁体   English   中英

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"/> 

并尝试如下访问“已修改”字段上方

  <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");
    }
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM