Reading values from application.properties Spring Boot

My Spring boot app has this application structure:

  • src
    • main
      • java
      • resources
        • application.properties

This is my application.properties file:

logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java

I have a class which requires the use of that language=java property. This is how I am trying to use it:

public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

That printed value is always “null” for some reason! I have also tried putting this on top of the class declaration:

@PropertySource(value = "classpath:application.properties")

Missing stereotype annotation on top of class

@Component
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

you can try to use @PropertySource and give it the path to property file, you can find the sample below:

@Component
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

Probably not the exact solution you’re looking for, but you can also declare a property source bean:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

It can be achieved in multiple ways, refer below.

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

OR

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

OK I figured it out with acts of desperation. I added the

@PropertySource("classpath:application.properties") 

attribute but it still wasn’t working for some reason.

I then deleted the “static” modifier and it worked!

I am not sure why it works without “static” being there but it does. If can explain it to me that would be wonderful because this is all confusing.