Reading values from application.properties Spring Boot

后端 未结 10 1691
无人及你
无人及你 2021-01-18 10:46

My Spring boot app has this application structure:

  • src
    • main
      • java
      • resources
        • application.properties
      <
相关标签:
10条回答
  • 2021-01-18 11:36

    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.

    0 讨论(0)
  • 2021-01-18 11:40

    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

    0 讨论(0)
  • 2021-01-18 11:41

    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

    0 讨论(0)
  • 2021-01-18 11:42

    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
    
    0 讨论(0)
提交回复
热议问题