I have a spring boot 2 app. I am trying to access my application properties file properties through spring Environment as well as @Value property, neither of them works.
@Autowired
Environment env;
logger.info(env.getProperty("app.environment"));
@Value("${app.environment}")
private String _env;
logger.info(_env);app.environment=LOCAL
Looks like spring boot is not detecting application.properties file at all.
What am I doing wrong here, Thanks in advance
21 Answer
If the injected property is null, it most probably means your bean has not been created yet. Spring boot injects values to bean properties only after the bean has been created.
Here's a simple experiment to demonstrate this behavior:
@Value("${spring.application.name}")
private String instanceApplicationName;
public UserController(@Value("${spring.application.name}") String appNameInConstructor) { System.out.println("Constructor app name: " + appNameInConstructor); System.out.println("Instance application name: " + this.instanceApplicationName);
}Which property would be null? instanceApplicationName or appNameInConstructor?
Yes, it's the instanceApplicationName property that's null because, the constructor is called first and the instance property has not been initialized yet. The appNameInConstructor correctly logs the application name.
So, where you reference the injected properties and how you inject them, both matter.
You can check the entire project here: .