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

前端 未结 2 1946
忘了有多久
忘了有多久 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: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> subRegionsMap;
        // (...) handling the SubRegion
    

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

    {subRegionCd=34, subRegionName=Southern Asia, subRegionDesc=, status=A}
    

提交回复
热议问题