简体   繁体   中英

How to map application property onto a map in SpringBoot?

I have this application.yaml file that has the following tag which is of interest:

   hardware:
      sensor:
        enable: false
        type: 'sensor'
      interface:
        enable: false
        type: 'interface-pcb'
      printer:
        enable: false
        type: mock #or bixolon or epson
      camera:
        enable: true
        type: mock #or joyusing
      fingerprint:
        enable: true
        type: mock #or secugen
      document:
        enable: true
        type: mock #or wentone
      barcode-scanner:
        enable: true
        type: mock #or honeywell
        timeout: 25 #must not be greater than 30

I want to be able to get the type of each hardware dynamically. I want to use a Map for this case that I could use.

A sample of the map I want:

"sensor": enable: true
        : type: mock

How can I achieve this using Spring Boot and Java 8?

Create a class that holds the properties and use @ConfigurationProperties annotation to map the properties in application.yml :

@Component
@ConfigurationProperties
public class ConfProperties {
    private Map<String, Hardware> hardware;

    public Map<String, Hardware> getHardware() {
        return hardware;
    }

    public void setHardware(Map<String, Hardware> hardware) {
        this.hardware = hardware;
    }

    public static class Hardware{
        private boolean enable;
        private String type;
        private int timeout;

        public boolean isEnable() {
            return enable;
        }

        public void setEnable(boolean enable) {
            this.enable = enable;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public int getTimeout() {
            return timeout;
        }

        public void setTimeout(int timeout) {
            this.timeout = timeout;
        }
    }
}

Use the configuration:

@Autowired
ConfProperties confProperties;

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