@ConfigurationProperties prefix not working

前端 未结 4 1285
南方客
南方客 2020-12-09 07:50

.yml file

cassandra:
    keyspaceApp:junit
solr:
    keyspaceApp:xyz

Bean

@Component
@ConfigurationProperties(prefix=\"ca         


        
4条回答
  •  遥遥无期
    2020-12-09 08:36

    General answer

    1. In your properties file (application.properties or application.yml)

    # In application.yaml
    a:
      b:
        c: some_string
    

    2. Declare your class:

    @Component
    @ConfigurationProperties(prefix = "a", ignoreUnknownFiels = false)
    public class MyClassA {
    
      public MyClassB theB;   // This name actually does not mean anything
                              // It can be anything      
      public void setTheB(MyClassB theB) {
        this.theB = theB;
      }
    
      public static MyClassB {
    
        public String theC;
    
        public void setTheC(String theC) {
          this.theC = theC;
        }
    
      }
    
    }
    

    3. Declare public setters! And this is crucial!

    Make sure to have these public methods declared in the above classes. Make sure they have "public" modifier.

    // In MyClassA
    public void setTheB(MyClassB theB) {
      this.theB = theB;
    }
    
    // In MyClassB
    public void setTheC(String theC) {
      this.theC = theC;
    }
    

    That's it.

    Final notes

    • The property names in your classes do not mean anything to Spring. It only uses public setters. I declared them public not to declare public getters here. Your properties may have any access modifiers.
    • Pay attention to the attribute "ignoreUnknownFields". Its default value is "true". When it is "false" it will throw exception if any of your properties in file "application.yml" was not bound to any class property. It will help you a lot during debugging.

提交回复
热议问题