简体   繁体   中英

Reading from yaml is showing null values

To read from yaml file i am doing the following

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("partners")
public class YAMLConfig {

    private Map<String,String> partners = new HashMap<>();

    public void setPartners(Map<String, String> partners) {
        this.partners = partners;
    }

    public Map<String, String> getPartners() {
        return partners;
    }
}

yaml file

person2:
  name: bbb
  addresses:
    to: jiang
    bit: su
partners:
  p1: wallet
  p2: wallet
  p3: wallet

And in other Java file i am Autowiring to get YamlConfig above

@Service
public class ObjectModificationService {

    @Autowired
    YAMLConfig yamlConfig;

    public  JSONObject modify(JSONObject jsonObject ) {
        String type  = yamlConfig.getPartners().get(partnerName.toLowerCase());
    }
}

I am not getting any type above , also checked yamlConfig.getPartners() in debug it is coming as null. I was following this tutorial: https://www.baeldung.com/spring-yaml , but then again IDE is showing error when i put ConfigurationProperties without ConfigurationProperties("partners").

In your yml configuration class, you have the properties annotation set to "partners", this means that the YAMLConfig class will attempt to read the partners section only. The "person2" section will not be read.

To retrieve the dependency injected values, simply call: yamlConfig.getPartners()

Also, be sure that the application.yml is in the resources directory and/or in the same directory as the .jar

you have specified Partners map accepts String values. so, try Map value formatted with quotes ('') in yaml config file

person2:
  name: bbb
  addresses:
    to: jiang
    bit: su
partners:
  p1: 'wallet'
  p2: 'wallet'
  p3: 'wallet'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM