I have a very simple Spring Boot app that I\'m trying to get working with some externalised configuration. I\'ve tried to follow the information on the spring boot documenta
Actually, For me below works fine.
@Component
public class MyBean {
public static String prop;
@Value("${some.prop}")
public void setProp(String prop) {
this.prop= prop;
}
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Now whereever i want, just invoke
MyBean.prop
it will return value.
You can use Environment
Class to get data :
@Autowired
private Environment env;
String prop= env.getProperty('some.prop');
If you're working in a large multi-module project, with several different application.properties
files, then try adding your value to the parent project's property file.
If you are unsure which is your parent project, check your project's pom.xml
file, for a <parent>
tag.
This solved the issue for me.
This answer may or may not be applicable to your case ... Once I had a similar symptom and I double checked my code many times and all looked good but the @Value
setting was still not taking effect. And then after doing File > Invalidate Cache / Restart
with my IntelliJ
(my IDE), the problem went away ...
This is very easy to try so may be worth a shot
Using Environment class we can get application. Properties values
@Autowired,
private Environment env;
and access using
String password =env.getProperty(your property key);
The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.
Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.