【问题标题】:How to map application property onto a map in SpringBoot?如何将应用程序属性映射到 Spring Boot 中的映射?
【发布时间】:2022-01-06 11:13:04
【问题描述】:

我有这个 application.yaml 文件,其中包含以下感兴趣的标签:

   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

我希望能够动态获取每个硬件的类型。我想在这种情况下使用我可以使用的地图。

我想要的地图样本:

"sensor": enable: true
        : type: mock

如何使用 Spring Boot 和 Java 8 实现这一点?

【问题讨论】:

  • 请注意我无法更改 YAML

标签: java spring spring-boot java-8 yaml


【解决方案1】:

创建一个保存属性的类,并使用@ConfigurationProperties注解映射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;
        }
    }
}

使用配置:

@Autowired
ConfProperties confProperties;

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2019-05-13
    • 2015-04-17
    • 1970-01-01
    • 2018-08-05
    • 2017-03-05
    相关资源
    最近更新 更多