Spring boot environment property returns null

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);

enter image description here

app.environment=LOCAL

Looks like spring boot is not detecting application.properties file at all.

What am I doing wrong here, Thanks in advance

2

1 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: .

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like