Search code examples
javaspringspring-mvcspring-annotations

Spring bean reference not working


I have the following 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;
        }
      }
    }

I have added:

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

and trying to access above "modified" field as below

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

in my application context. But I keep getting the following error:

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

Not sure why i get this error?


Solution

  • When Spring creates the object it uses the default constructor. It can't set the property until after it constructs it. Instead of what you have, try this to see if the value is being set.

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