Reading a map from yaml in Java getting null

前端 未结 1 1888
无人共我
无人共我 2020-12-11 06:12

I am getting a problem in reading my yaml through java, using spring. Let me show the code first

@Component
@EnableConfigurationProperties
@ConfigurationProp         


        
相关标签:
1条回答
  • 2020-12-11 06:54

    I had the same problem with different generic types and I solved it by initializing the map member and remove the setter method, e.g.:

    @Component
    @EnableConfigurationProperties
    @ConfigurationProperties(prefix = "countries")
    public class UserLimitReader{
        private Map<String, Integer> orders = new HashMap<>();
    
        private Map<String, Integer> requests = new HashMap<>();
    
        public Map<String, Integer> getOrders() {
            return orders;
        }
        ...
    }
    

    Please note I used java 7 diamond operator and change the member type to Map instead of HashMap.

    IMPORTANT: In my code, I use Spring's configuration class instead of XML and moved the EnableConfigurationProperties to the configuration class. In your case it should be something like:

    @Configuration
    @EnableConfigurationProperties(value = {UserLimitReader.class})
    public class SpringConfiguration {
        ...
    }
    
    @ConfigurationProperties(prefix = "countries", locations: "classpath:config/application.yaml")
    public class UserLimitReader {
        ...
    }
    

    Don't know how you configure it using XML, however as I wrote in my comments I still think you should make sure Spring's finds your class using component scan or something alike.

    @Value work as Spring loads the YAML file without any problem using your context file, however it does not mean UserLimitReader file is loaded and configured by Spring.

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