简体   繁体   中英

How to read properties with special characters from application.yml in springboot

application.yml

mobile-type:
  mobile-codes:
    BlackBerry: BBSS
    Samsung: SAMS
    Samsung+Vodafone: SAMSVV
  1. While reading (Samsung+Vodafone)key from application yml file , we are getting. concatenated String format as 'SamsungVodafone' .

  2. Morever we heve tried "Samsung'/+'Vodafone": SAMSVV but the result was same and we have tried other symbol such as '-' so its working fine .

  3. For reading key and value from application yml file . we have written below code.

import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 @ConfigurationProperties(prefix = "mobile-type")
    @Component
    public class mobileTypeConfig {


        Map<String, String> mobileCodes;

        public Map<String, String> getMobileCodes() {
            return mobileCodes;
        }

        public void setMobileCodes(Map<String, String> mobileCodes) {
            this.mobileCodes= mobileCodes;
        }
}

Note :Spring Boot Version 2.0.6.RELEASE

Use square brackets not to escape any character and encode that in double quotes

mobile-type:
  mobile-codes:
    BlackBerry: BBSS
    Samsung: SAMS
    "[Samsung+Vodafone]": SAMSVV

Output

{BlackBerry=BBSS, Samsung=SAMS, Samsung+Vodafone=SAMSVV}

Binding

When binding to Map properties, if the key contains anything other than lowercase alpha-numeric characters or -, you need to use the bracket notation so that the original value is preserved. If the key is not surrounded by [], any characters that are not alpha-numeric or - are removed. For example, consider binding the following properties to a Map:

acme:
  map:
   "[/key1]": value1
   "[/key2]": value2

please keep in mind that the left side is a yml key, not an arbitrary string. my suggestion or your usecase would be to have a map with both on the right side such as:

foo:
  - name: "Samsung+Vodafone"
    code: "SAMSVV"
  - name: "BlackBerry"
    code: "BBMS"
  - name: "Samsung"
    codes: 
     - "SAMS"
     - "SMG"

you will have to change your class structure slightly, but you could actually reconstruct your initial approach from that.

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