首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将应用程序属性映射到SpringBoot中的映射上?

如何将应用程序属性映射到SpringBoot中的映射上?
EN

Stack Overflow用户
提问于 2022-01-06 11:13:04
回答 1查看 80关注 0票数 0

我有这个application.yaml文件,它有下面的标记,这是值得关注的:

代码语言:javascript
复制
   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

我希望能够动态地获得每个硬件的类型。我想用地图来处理这个案子,我可以用它。

我想要的地图样本:

代码语言:javascript
复制
"sensor": enable: true
        : type: mock

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

EN

回答 1

Stack Overflow用户

发布于 2022-01-06 11:42:16

创建一个保存属性的类,并使用@ConfigurationProperties注释映射application.yml中的属性

代码语言:javascript
复制
@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;
        }
    }
}

使用以下配置:

代码语言:javascript
复制
@Autowired
ConfProperties confProperties;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70606252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档