0

I am new to springmvc, so the question may sounds dumb.

I have similar issue to this Spring Boot: @Value returns always null. Example that i have:

System Properties

<sysproperty key="bar" value="bar_value" />

Bean Configuration

@Configuration
public class Foo {
    @Value("${bar}")
    private String bar;
  
    @Bean(name = "getBar")
    public String getBar() { 
        return bar;
    }
}

Access Bean (index.jsp)

String bar = webApplicationContext.getBean("getBar", String.class); // returns null instead of "bar_value"

However, if i change the Bean Configuration to

@Configuration
public class Foo {
    @Value("${bar}")
    @Bean(name = "getBar")
    public String getBar(String bar) { 
        return bar;
    }
}

and then accessing it, the returned value is correct, what could be the reason of this? I know that things are controlled by the framework so i don't have much visibility about the instantiation process of the app, help is well appreciated.

Allen
  • 4,431
  • 2
  • 27
  • 39

1 Answers1

1

Please make use of Setter Injection. Hope it will resolve your issue.


public class Foo {
    
    private String bar;
    
    @Autowired
    public setBar(@Value("${bar}") String bar) {
        this.bar = bar;
    }
    
    // standard getter
    @Bean(name = "getBar")
    public String getBar() { 
        return bar;
    }
}
priyranjan
  • 674
  • 6
  • 15