Unable to read values from property file using @value or by using Autowired to Enviroment

Aman Vyas :

I have two properties file in my Spring boot project. And I am able to read the properties from both in one class. But the same value when I am trying to read from a different class using @Value or by Autowired Environment, it is giving me null.

    prop.name=test /*   property file value */

    @Component
    public class TestUtil { // This is the class giving me null value

        @Value("${prop.name}")
        String st;

        public String getTestString()
        {
            System.out.println(st+ " ***");
            return st;

        }
    }

//Using @Autowired Enviroment
public class TestUtil {

    @Autowired
    private Environment env;


    public String getTestString()
    {
        System.out.println(env.getProperty("prop.name")+ " ***");
        return env.getProperty("prop.name");

    }
}

/* Class below giving me value from properties file*/

        public class JsonWriter extends JsonResponseWriter {

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

      /* Some method*/
       System.err.println("from JsonWriter  "+contentsMenus);

Here I am autowiring

@Service
public class ResponseUtil {
    @Autowired
     private TestUtil util ;

In the above class I am using autowired

Aman Vyas :

After M. Deinum comments analyzed the code and found that the first class from where I was calling another class was not autowired.So after autowiring the class it worked. Thanks a lot @M.Deinum and all the users who answered my question.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88853&siteId=1