Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Property Injection in a final attribute @Value - Java

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?

like image 563
NightWolf Avatar asked Aug 20 '11 07:08

NightWolf


People also ask

Can we use @value for final variable?

You cannot. The only way to make this work is put the @Value annotation on an attribute int he constructor and then set the url in the constructor.

What does @value mean in Spring?

@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.

What is @value annotation in Spring?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.

How do you inject a value to a static field?

Solution First, PropertyController, which is a RestController, is being initialized by Spring. Afterward, Spring searches for the Value annotated fields and methods. Spring uses dependency injection to populate the specific value when it finds the @Value annotation.


Video Answer


2 Answers

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.

like image 133
Sean Patrick Floyd Avatar answered Oct 02 '22 01:10

Sean Patrick Floyd


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);     } } 
like image 34
Austin Poole Avatar answered Oct 02 '22 01:10

Austin Poole