zno2

@ConfigurationProperties 前缀注入属性

 

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix="zoo")
@Configuration
public class ZooConfig {
    
    private String name;

    private Map<String,Animal> animals = new LinkedHashMap<>();;


    public Map<String, Animal> getAnimals() {
        return animals;
    }

    public void setAnimals(Map<String, Animal> animals) {
        this.animals = animals;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static class Animal {
        private String name;
        private Integer type;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
}

 

zoo.name = 我的动物园
zoo.animals.dog.name = 大黄
zoo.animals.dog.tYpe = 1
zoo.animals.cat.name = 咪咪
zoo.animals.cat.tYPE = 2

 

使用:

        ZooConfig zooConfig = ap.getBean(ZooConfig.class);
        Animal animal = zooConfig.getAnimals().get("cat");

 

备注:属性不区分大小写,比如 cat.type  或 cat.type 都能注入到 type 中

 

参考:

org.springframework.cloud.netflix.zuul.filters.ZuulProperties

org.springframework.boot.autoconfigure.cache.CacheProperties

 

补充:2022-08-03

不支持 zoo.a.b 支持 zoo.a-b 或 zoo.ab

 

posted on 2023-07-13 18:01  zno2  阅读(69)  评论(0编辑  收藏  举报

导航