Reading values from application.properties Spring Boot
Asked Answered
J

12

6

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")
Joettejoey answered 1/8, 2017 at 4:8 Comment(1)
If my answer provided you the solution, please accept it.Maighdiln
M
18

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

}
Maighdiln answered 1/8, 2017 at 5:45 Comment(8)
It is still not working with the @PropertySource annotation. I am not sure why but I guess it cannot find the application.properties file? Is there a way to check what path the "classpath" refers to?Joettejoey
@aBrokenSniper, is application.properties available in classpath? what is the path of application.properties in your project?Maighdiln
@aBrokenSniper, alternatively you can use file path as well.. @PropertySource("file:/path/to/application.properties")Maighdiln
I put the application.properties in the default location suggested by spring docs: under src>main>resources>application.properties. It should be picked up by default right?Joettejoey
Yes, it should be picked up by default. If it doesn't then, try with file path as I commented aboveMaighdiln
Actually I am fairly certain it is being read as I changed the logging level in that application.properties file and the logging level changed for my app. Could it be the way I declared the variable in the file?Joettejoey
@PropertySource("classpath:application.properties") have you had it like this?Maighdiln
Yep. Also I just figured it out (still not sure why it works)! See my answer below! Thank you for your help!Joettejoey
C
5

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.

Cathee answered 22/5, 2018 at 1:15 Comment(1)
is it still possible for any-name.properties ?Angelia
D
3

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);
    }
}
Dynast answered 1/8, 2017 at 4:10 Comment(2)
Does it have to be a component? I was reading this tutorial: link and they didn't use a Component. Is there any way I can grab the value from the properties file without using any stereotype annotations for the class?Joettejoey
it can be any one of the spring stereotype annotations. In that case you have get it from Environment by accessing the ApplicationContext statically inside your class or else make use of System.getProperty interms of JVM property.Dynast
P
3

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.

Pounds answered 17/11, 2017 at 22:28 Comment(0)
F
1

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

Fabulist answered 1/8, 2017 at 5:27 Comment(0)
J
1

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.

Joettejoey answered 1/8, 2017 at 17:32 Comment(1)
#10939029Jeanejeanelle
O
1

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
Ousley answered 5/12, 2017 at 15:32 Comment(0)
P
1

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.

Platino answered 14/1, 2019 at 21:41 Comment(0)
C
1

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.

Chuckhole answered 17/2, 2021 at 9:41 Comment(0)
S
0

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);
    }
}
Swayne answered 1/8, 2017 at 4:18 Comment(0)
T
0

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

Toper answered 25/6, 2018 at 8:1 Comment(0)
A
0

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;
    }
Allamerican answered 16/3, 2022 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.