zoukankan      html  css  js  c++  java
  • springbooot 项目读取yml配置文件(自定义)

    1.需要引入的依赖包

    <!--读取yml配置文件的依赖-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
    </dependency>

    2.yml配置文件(myproperties一定不可以有大写的,不然会报错)

    myproperties: #自定义的属性和值
    simpleProp: hellow
    arrayProps: 1,2,3
    listProp1:
    - name: 123
    value: 123Value
    - name: 456
    value: 456Value
    listProp2:
    12345,
    12345
    mapProps:
    key1: 123
    key2: 123

    3.配置类

    @Component
    @ConfigurationProperties(prefix="myproperties") //接收application.yml中的myProps下面的属性
    public class MyProps {
    private String simpleProp;
    private String[] arrayProps;
    private List<Map<String, String>> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
    private List<String> listProp2 = new ArrayList<>(); //接收prop2里面的属性值
    private Map<String, String> mapProps = new HashMap<>(); //接收prop1里面的属性值

    public String getSimpleProp() {
    return simpleProp;
    }

    //String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要
    public void setSimpleProp(String simpleProp) {
    this.simpleProp = simpleProp;
    }

    public List<Map<String, String>> getListProp1() {
    return listProp1;
    }
    public List<String> getListProp2() {
    return listProp2;
    }

    public String[] getArrayProps() {
    return arrayProps;
    }

    public void setArrayProps(String[] arrayProps) {
    this.arrayProps = arrayProps;
    }

    public Map<String, String> getMapProps() {
    return mapProps;
    }

    public void setMapProps(Map<String, String> mapProps) {
    this.mapProps = mapProps;
    }

    4.测试

    注入配置类

    @Autowired
    private MyProps myProps;
    @RequestMapping("properties")
    public Object getProperties() {
    System.out.println("simpleProp: " + myProps.getSimpleProp());
    System.out.println("arrayProps: " + JSON.toJSONString(myProps.getArrayProps()));
    System.out.println("listProp1: " + JSON.toJSONString(myProps.getListProp1()));
    System.out.println("listProp2: " + JSON.toJSONString(myProps.getListProp2()));
    System.out.println("mapProps: " + JSON.toJSONString(myProps.getMapProps()));
    List<String> listProp2 = myProps.getListProp2();
    System.out.println(listProp2);
    return null;
    }

    结果如下:

    
    


  • 相关阅读:
    leetcode5
    leetcode4
    maven笔记
    枚举使用笔记
    List遍历删除解决方案:遍历删除,迭代删除,removeIf
    java笔记(web部分)
    webview使用
    json数据格式+gson解析json问题总结
    android:layout_weight的简单使用
    欢迎界面效果
  • 原文地址:https://www.cnblogs.com/guagua-join-1/p/10271251.html
Copyright © 2011-2022 走看看