Spring Boot application.properties value not populating

后端 未结 8 546
孤街浪徒
孤街浪徒 2020-12-04 11:41

I have a very simple Spring Boot app that I\'m trying to get working with some externalised configuration. I\'ve tried to follow the information on the spring boot documenta

相关标签:
8条回答
  • 2020-12-04 12:16

    Actually, For me below works fine.

    @Component
    public class MyBean {
    
       public static String prop;
    
       @Value("${some.prop}")
       public void setProp(String prop) {
          this.prop= prop;
       }
    
       public MyBean() {
    
       }
    
       @PostConstruct
       public void init() {
          System.out.println("================== " + prop + "================== ");
       }
    

    }

    Now whereever i want, just invoke

    MyBean.prop

    it will return value.

    0 讨论(0)
  • 2020-12-04 12:16

    You can use Environment Class to get data :

    @Autowired
    private Environment env;
    String prop= env.getProperty('some.prop');
    
    0 讨论(0)
  • 2020-12-04 12:17

    If you're working in a large multi-module project, with several different application.properties files, then try adding your value to the parent project's property file.

    If you are unsure which is your parent project, check your project's pom.xml file, for a <parent> tag.

    This solved the issue for me.

    0 讨论(0)
  • 2020-12-04 12:20

    This answer may or may not be applicable to your case ... Once I had a similar symptom and I double checked my code many times and all looked good but the @Value setting was still not taking effect. And then after doing File > Invalidate Cache / Restart with my IntelliJ (my IDE), the problem went away ...

    This is very easy to try so may be worth a shot

    0 讨论(0)
  • 2020-12-04 12:25

    Using Environment class we can get application. Properties values

    @Autowired,

    private Environment env;
    

    and access using

    String password =env.getProperty(your property key);
    
    0 讨论(0)
  • 2020-12-04 12:26

    The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.

    Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.

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