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、分离配置文件同时可以用于分离别的配置信息。

原文地址:https://www.cnblogs.com/linkstar/p/9475725.html