Search code examples
javaspring-bootspring-annotations

access the value from app.properties and store in variable using @Value Springboot


I want to access the variable value that is stored in application.properties of Spring Boot App. Using the following code I am able to access the value in variable

application.properties

path.animals=top/cat/white

Code

import org.springframework.beans.factory.annotation.Value;

    @Value("${path.animals}")
    private String FOLDER_PATH;
    private String absolute_folder_path = "/home/johnDoe/Documents/" + FOLDER_PATH;

When I print them both variables on screen I got

FOLDER_PATH : top/cat/white

absolute_folder_path :/home/johnDoe/Documents/null

I need the absolute_folder_path should be /home/johnDoe/Documents/top/cat/white.

Note : Both variables are declared outside the method. These are global variable


Solution

  • This issue is happening because absolute_folder_path did not get the value of Folder Path yet. And this is because of the way Spring injects those values. Where are you trying to print them?

    You can try autowiring with a constructor and setting the value of absolute_folder_path in your constructor.

    Example

    public class Test{
    
        private String FOLDER_PATH;
        private String absolute_folder_path;
    
    @Autowired
      public Test(@Value("${path.animals}") String folderPath){
        FOLDER_PATH= folderPath;
        absolute_folder_path = "/home/johnDoe/Documents/" + folderPath;
      }
    
    }