zoukankan      html  css  js  c++  java
  • SpringBoot读取yml中的配置,并分离配置文件

    前言

    在项目中经常遇到需要读取配置文件中的配置信息,这些配置信息之所以不写在代码中是因为实际项目发布或者部署之后会进行更改,而如果写在代码中编译之后没有办法进行修改。
    之前使用的是properties进行的配置和读取的。
    而在SpringBoot中我们采用yml的配置时也需要读取配置文件中的信息。
    同时因为这样会导致配置文件增多,所以我们需要分离配置文件。

    github:https://github.com/LinkinStars/springBootTemplate

    分离配置文件

    在application.yml使用include加载不同的配置文件,如下是加载application-config.yml配置文件

    spring:
      # 选择加载不同环境的配置文件
      profiles:
        active: dev
        include: config

    在application-config.yml配置文件中加入测试参数
    demo:
      id: 1
      val: 123

    读取配置文件

    使用@Component和@ConfigurationProperties注解实现,如下

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    /**
    * 读取配置文件中的信息
    * @author LinkinStar
    */
    @Component
    @ConfigurationProperties(prefix = "demo")
    public class DemoConfig {
    private int id;
    private String val;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getVal() {
        return val;
    }
    
    public void setVal(String val) {
        this.val = val;
    }
    }

    如何使用

    /**
    * Demo读取配置测试
    * @author LinkinStar
    */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class DemoConfigTest {
    
    @Autowired
    private DemoConfig demoConfig;
    
    @Test
    public void getDemoConfig(){
        System.out.println(demoConfig.getId());
        System.out.println(demoConfig.getVal());
    }
    }

    总结

    1、这些配置主要用于存放那些容易被修改的配置。
    2、@ConfigurationProperties和@Value的区别是:前一个作用于对象也就是批量的注入配置信息,而后者是单个指定。
    3、分离配置文件同时可以用于分离别的配置信息。

  • 相关阅读:
    html实现滚动播报(原生JS实现)
    移动端H5页面惯性滑动监听
    简单线条、任意填充色的小图标(含自制方法)
    git和github新手安装使用教程(三步入门)
    node.js的安装配置——前端的配置
    Sublime Text 3 一些简单使用
    $.ajax() 方法的理解
    前端知识点
    (6)一些工作和生活的经验分享,以后还会不断补充添加
    (5.1)Opencv库学习第二部分
  • 原文地址:https://www.cnblogs.com/linkstar/p/9475725.html
Copyright © 2011-2022 走看看