Spring Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


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:

private String name;

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

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:

public class PropertyController {

    private String name;

    private static String NAME_STATIC;

    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.

Spring bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

Inline Feedbacks
View all comments
8 months ago

Hi Guys,
Aren’t we updating a static value from a non-static method, will it not cause issues when multiple instances are in use?

Loredana Crusoveanu
8 months ago
Reply to  Santhosh

Hi Santosh,
Yes in general, of course, you’re right.
That’s why we emphasize that you should try to refactor your code first.
On the other hand, remember that Spring beans are singletons by default so we should be rather on the safe side.
Anyway, the bottom line is – just because you can do something doesn’t mean you should 🙂

Comments are closed on this article!