Spring SpEL - Expression Language to create Map of String and Custom Object

前端 未结 2 1945
忘了有多久
忘了有多久 2021-01-17 02:38

I\'m using Spring Boot example to read the following from the properties file.

sub.region.data={\\
    AF: {\'subRegionCd\' : \'34\', \'subR         


        
相关标签:
2条回答
  • 2021-01-17 03:28

    Looks like you made a mistake after 'subRegionDesc',, I think you mean using colon, not a comma here

    With spring boot I suggest you to use ConfigurationProperties, instead of @Value.

    For example, in this case you have to:

    1. put @EnableConfigurationProperties(SubRegionConfig.class) to one of your spring configuration class.

    2. Create config class:

      @ConfigurationProperties(prefix = "sub.region")
      public static class SubRegionConfig {
          private Map<String, SubRegion> data;
          //getters and setters
      } 
      
    3. Use .yml instead of .properties, like that:

      sub:
        region:
         data:
           AF:
            subRegionCd: '34'
            subRegionName: 'Southern Asia'
            subRegionDesc: ''
            subRegionStatus: 'A'
      
    4. After that you can get every properties you want from SubRegionConfing

      @Autowired
      private SubRegionConfig subRegionConfig;
      

    ConfigurationsProperties is more complex, but more flexible and preferrable to use in most cases.

    0 讨论(0)
  • 2021-01-17 03:34

    The #{} operator sends data into spEL parser, what means it will try to convert data into its know types, based on spEL syntax as shown here in Spring Docs.

    What happens is that the compiler is unable to convert any data into a SubRegion object:

    Cannot convert value of type 'java.util.Collections$UnmodifiableMap' to required type 'com.xxxxxx.model.SubRegion': no matching editors or conversion strategy found

    A simple workaround is to nest two Map Objects so you can populate your SubRegion objects after retrieving the values.

    yourMap={'key1':{'nestedMapKey1:value', 'nestedMapKey2:value2'}}
    

    In your .properties file with your code:

    sub.region.data={'AF':{'subRegionCd':'34', 'subRegionName':'Southern Asia', 'subRegionDesc':'', 'status':'A'}}
    

    and then, in your code:

        @Value("#{${sub.region.data}}")
        private Map<String, Map<String, String>> subRegionsMap;
        // (...) handling the SubRegion
    

    My System.out.println(subRegionMap.get("AF"); outputed:

    {subRegionCd=34, subRegionName=Southern Asia, subRegionDesc=, status=A}
    
    0 讨论(0)
提交回复
热议问题