1. Overview

In this tutorial, we'll see how we can inject a value from a Java properties file to a static field with Spring.

2. Problem

To begin with, let's imagine that we set a property to a properties file:

name = Inject a value to a static field

Afterward, we want to inject its value to an instance variable.

That usually can be done by using the @Value annotation on an instance field:

@Value("${name}")
private String name;

However, when we try to apply it to a static field, we'll find that it will still be null:

@Value("${name}")
private static String NAME_NULL;

That's because Spring doesn't support @Value on static fields.

Now, truthfully, this is an odd position for our code to be in, and we ought to first consider refactoring. But, let's see how we can make this work.

3. Solution

First, let's declare the static variable we want to inject NAME_STATIC.

Afterward, we'll create a setter method, called setNameStatic and annotate it with the @Value annotation:

@RestController
public class PropertyController {

    @Value("${name}")
    private String name;

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Let's try and make sense of what's happening above.

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. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

4. Conclusion

In this short tutorial, we've looked at how to inject a value from a properties file into a static variable. This is a route we can consider when our attempts to refactor fail.

As always, the code is available over on GitHub.