Spring Property Injection in a final attribute @Value - Java

51,559

Solution 1

The only way you can inject values into a final field is through Constructor Injection. Everything else would be an awful hack on Spring's side.

Solution 2

If you are looking for an example here is one:

public class Test {
    private final String value;

    public Test(@Value("${some.value}") String value){
        this.value=value;
        System.out.println(this.value);
    }
}
Share:
51,559

Related videos on Youtube

NightWolf
Author by

NightWolf

Updated on July 09, 2022

Comments

  • NightWolf
    NightWolf almost 2 years

    A simple question on Spring injection from a properties file for a final attribute.

    I have a properties file which I want to store a file path in. Generally when I use properties files I setup class attributes using something like this:

    private @Value("#{someProps['prop.field']}") String someAttrib ;
    

    Then in my spring.xml I would have something like:

    <util:properties id="someProps"   
        location="classpath:/META-INF/properties/somePropFile.properties" />
    

    This works well, is simple and makes code nice and neat. But I'm not sure what is the neatest pattern to use when trying to inject properties values into final class attributes?

    Obviously something like:

    private static final @Value("#{fileProps['dict.english']}") String DICT_PATH; 
    

    will not work. Is there another way?

    • skaffman
      skaffman over 12 years
      No, the two approaches are incompatible.
  • wheeler
    wheeler about 7 years
    Is there an example of this?
  • giannis christofakis
    giannis christofakis almost 4 years
    How are you gonna initialize this class? Are you gonna annotate it as a Component and let the container do it or in any other way ?
  • Austin Poole
    Austin Poole almost 4 years
    Using @Component annotation or any of the other stereotypes will work
  • giannis christofakis
    giannis christofakis almost 4 years
    Any idea how to do the same in a static property?
  • Austin Poole
    Austin Poole almost 4 years
    You can't. You can only initialize a static final property in two ways. In a static block or in the declaration statement. static { STATIC_VARIABLE = "value";} or private static final String FOO = "bar"