1

environment properties are there in application.properties

application.properties

app.mail.allowedDomains=gmail

in class

@Autowired
private Environment env;

@Value("${app.mail.allowedDomains}")
private static String allowedDomainsForMail;

@Value("${app.mail.allowedDomains:nothing}")
private static String allowedDomainsForMail2;

public void printProperties() {
    System.out.println("Inside impl");
    System.out.println("@Value:\t" + allowedDomainsForMail);
    System.out.println("@Value:\t" + allowedDomainsForMail2);
    System.out.println("Env:\t" + env.getProperty("app.mail.allowedDomains"));
}

Output

Inside impl

@Value: null
@Value: null
Env:    gmail

It is not even setting "nothing"(default value if not found) in 2nd scenario. But from env it's printing

I even tried with @ConfigurationProperties in main class of package.

No success.

Is value fetched from env file on each hit or on app load only it will load?

Value from org.springframework.beans.factory.annotation.Value

Satish Patro
  • 3,645
  • 2
  • 27
  • 53
  • 6
    The problem is the use of static fields. See also https://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field – FredvN Nov 09 '19 at 10:43

2 Answers2

3

Spring does not allow inject into a static field. Overall it's considered not a good practice. Below a few links which might help you to understand why.

link#1 link#2

Remove static and the injection should happen, since the env Environment was injected.

vzhemevko
  • 815
  • 8
  • 25
2

The Spring doesn't support static field injection. Also @Value annotation is also not the best practice.

The best way is to use @ConfigurationProperties annotation and bind it with application properties. It will help you to mock Configration Bean in Unit tests, instead of use reflection for @Value injection

Alex Faster
  • 199
  • 10