读取spring boot 的yml配置文件

yml的配置文件格式如下:

# 应用名称
application:
  name: PLAY

# 环境配置
spring:
  profiles:
    active: dev   #开发环境: application-dev.yml
#    active: prod  #生产环境
#    active: test  #测试环境

  # 设置编码
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true

# 用户永久token
user:
  permanent:
    authorization: play


# 服务器端口,api路径
server:
  port: 8080
  servlet:
    context-path: /play/api/

# api版本号
api:
  version:
    latest: v0.0.1

# 时区设置
time:
  zone: Asia/Shanghai

读取配置的java类定义如下:

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 公共配置读取
 *
 * @author zhangxz
 * 2019/10/28
 */

@Component
@Getter
public class CommProp {

    /**
     * 用户认证信息
     */
    @Value("${user.permanent.authorization}")
    private String userPermanentAuthorization;

    /**
     * api版本号
     */
    @Value("${api.version.latest}")
    private String apiVersionLatest;

    /**
     * 时区设置
     */
    @Value("${time.zone}")
    private String timeZone;

    /**
     * 应用名称
     */
    @Value("${application.name}")
    private String applicationName;

}

使用的时候,通过依赖注入直接从spring容器拿取该类的实例即可。

结束

原文地址:https://www.cnblogs.com/zhangxuezhi/p/11812540.html