0

I have an environment variable RESOURCES_FOLDER. Which i want to read in a class inside my Springboot application

@Value("${RESOURCES_FOLDER}")
private static String resourcesFolder;

When I try printing the value it gives null instead of printing the actual path in my environment variable. Can someone please help me with this ??

Anuja Barve
  • 300
  • 1
  • 4
  • 23

2 Answers2

2

Spring does not allow injecting values into static fields. You have a few options to circumvent this restriction:

  1. Create a non-static setter. This is not a particularly good approach, as resourceFolder will be shared by all instances of a class. Nevertheless, you should be able to achieve it by:
public class SomeClass {
    ...

    public static String resourcesFolder;

    @Value("${RESOURCES_FOLDER}")
    public void setResourcesFolder(String resourcesFolder) {
        this.resourcesFolder = resourcesFolder;
    }

    ...
}
  1. Declare the field as non static. For this, ask yourself: do you really, really need the field to be static? Most of the time non-static field is good enough.
  2. Create a separate @ConfigurationProperties class, declare fields as private non-static, create getters/setters for it and inject the class wherever you need the variable. This is a very composable and testable approach, which I would recommend, especially if you have quite a few related properties.

Alternatively, please refer to the other similar questions: 1, 2.

cegas
  • 2,823
  • 3
  • 16
  • 16
0

Add your environment variable name in the application.properties file by:

RESOURCE_FOLDER_PATH =${RESOURCES_FOLDER}

Here RESOURCES_FOLDER is the name of your environment variable.

Then access the environment variable in the java class by using @value annotation.

public class AccessEnvironmentVariable{

@Value("${RESOURCE_FOLDER_PATH}")
private String RESOURCE_FOLDER;

private void displayEnvironmentVariable(){
    System.out.println("Your environment variable Resource Folder: "+RESOURCE_FOLDER);
}

}

Bishal Jaiswal
  • 1,684
  • 13
  • 15