Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 586
Karan Avatar asked Aug 01 '17 04:08

Karan


2 Answers

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

}
like image 74
Anil Kumar Athuluri Avatar answered Oct 31 '22 03:10

Anil Kumar Athuluri


If you are using Spring boot you do not need @PropertySource("classpath:application.properties") if you are using spring boot starter parent , just remove the static keyword and it should start working.

like image 20
Anindya Mukherjee Avatar answered Oct 31 '22 03:10

Anindya Mukherjee