Reading values from application.properties Spring Boot

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

My Spring boot app has this application structure:

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

    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.

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

    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.

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

    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");
        }
    
    }
    
    0 讨论(0)
  • 2021-01-18 11:29

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 11:30

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 11:31

    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.

    0 讨论(0)
提交回复
热议问题