Karan
Karan

Reputation: 1400

Reading values from application.properties Spring Boot

My Spring boot app has this application structure:

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

Upvotes: 6

Views: 75822

Answers (12)

pallavi
pallavi

Reputation: 95

You do not need to specify the properties file if you are using the default application.properties file in src/main/resources directory. It will be auto-detected.

You need to add @Value in the constructor as the value injection doesn't happen before constructor is called.

    private static String newLang;

    public EntityManager(@Value("${language}") newLang){
        this.newLang=newLang;
    }

Upvotes: 0

Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27256

The value from the properties file is ALWAYS null IF you are trying to read it BEFORE the Spring Bean has been fully initialized, for example, when calling the value from the constructor. This was the case for me.

To get past this, use the @PostConstruct annotation like this:

@Configuration
public class CustomConfiguration {


     Logger logger = Logger.getLogger(CustomConfiguration.class.getSimpleName());

     @Value("${test.value}")
     private String testValue;

      @PostConstruct
      public void initializeApplication() {
        logger.info("============================================>"+testValue);
      }

Just make sure you are not trying to use the value of testValue anywhere else before initializeApplication is called.

Upvotes: 1

VC2019
VC2019

Reputation: 465

As provided in the 2nd answer above I was indeed using the spring boot, so removed the static keyword and that resolved my issue. Make sure you don't have static for the property defined with @Value.

Upvotes: 1

hello_earth
hello_earth

Reputation: 1562

in my case, the same problem had a slightly different cause - i had a class with a static instance variable (the old usual way we used to implement a Singleton pattern), into which i wanted to inject an entry from application.properties (probably the "static" thing was why the property could not be found - with no errors no anything :/).

moreover this class was in a totally different package from the class declared as @SpringBootApplication. i understood that package names and locations have to be taken into serious consideration with Spring Boot and automatic component scanning. my 5 cent

Upvotes: 0

Anindya Mukherjee
Anindya Mukherjee

Reputation: 107

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.

Upvotes: 5

BazSTR
BazSTR

Reputation: 137

create you beans

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

    @Autowired
    Environment env;

    @Bean
    public IApplicationBeanService getService(){
        return new ApplicationBeansService(env);
    }
}

and then in service costructor

@Service
public class ApplicationBeansService implements IApplicationBeanService {
...
   public ApplicationBeansService(Environment env){
      ...
      String value = env.getProperty("your.value")
      ...
   }
...
}

don't forget fill your application.properties:

your.value = some-string-value

Upvotes: 1

Mayank Madhav
Mayank Madhav

Reputation: 499

Sometimes, the classpath entry for src/main/resources contains an exclude tag. If application.properties is present in this list of excluded items then @PropertySource("classpath:application.properties") will not be able to find the property file.

Either remove the exclude entry from [.classpath][1] file for src/main/resources manually, or use the Configure build path option in Eclipse and go to Source tab. Then remove the exclude entry from src.

Upvotes: 3

Karan
Karan

Reputation: 1400

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.

Upvotes: 1

Anil Kumar Athuluri
Anil Kumar Athuluri

Reputation: 653

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

}

Upvotes: 18

Ognjen Mišić
Ognjen Mišić

Reputation: 1426

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

Upvotes: 1

Mayank Sharma
Mayank Sharma

Reputation: 443

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

Upvotes: 0

Barath
Barath

Reputation: 5283

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

Upvotes: 3

Related Questions