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
You're missing a dollar sign in Value
annotation. This should do the work:
@Value("${prop.name}")
use $ in property names: Eg:
@Value("${prop.name}")
Try that piece of code
@Component
public class TestUtil {
@Autowired
private Environment env;
public String getTestString(){
System.out.println(env.getProperty("prop.name")+ " ***");
return env.getProperty("prop.name");
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.