• 喜欢前端以及PHP的朋友们可以加PHP同好会QQ群 点击加入qq群
  • 最近在写一个项目---"小A微信托管平台",大家可以去帮忙测试一下!功能在不断完善中,敬请关注!点击进入
  • 本站使用了PHP8.1与HTTP2.0协议,速度简直超级快有木有?

Spring Boot2 学习笔记之获取配置参数(三)

后端 Mr.Adam 4年前 (2021-03-30) 1528次浏览 已收录 0个评论

Spring Boot2 学习笔记之获取配置参数(三)

Spring Boot2 学习笔记之获取配置参数(三)

在 spring boot 中的配置文件有两种形式: application.propertiesapplication.yml
推荐使用yml的格式文件进行配置

大概结构如下:

spring:
  application:
    name: ${APP_NAME:unknow_name}
  devtools:
    restart:
      exclude: static/**,public/**
      enabled: true
server:
  port: ${APP_PORT:8080}

storage:
  local:
    # 文件存储根目录:
    root-dir: ${STORAGE_LOCAL_ROOT:D:/storage}
    # 最大文件大小,默认 1000K:
    max-size: ${STORAGE_LOCAL_MAX_SIZE:1024000}
    # 是否允许空文件:
    allow-empty: false
    # 允许的文件类型:
    allow-types: jpg, png, gif

获取配置信息

如何在控制器中获取配置文件中的信息呢?

//通过 value 获取
@Value("${ip}")
public String ip;

首先编写一个configuration

//StorageConfiguration
@Data
@Configuration
@ConfigurationProperties("storage.local")
public class StorageConfiguration {

    private String rootDir;

    private int maxSize;

    private boolean allowEmpty;

    private List<String> allowTypes;
}

在控制器中可以使用如下方式获取配置文件

    @Autowired
    StorageConfiguration storageConfig;
    @GetMapping("get_option")
    public Map<String,Object> get_option(){

        Map<String,Object> map = new HashMap<>();
        map.put("allow_types",storageConfig.getAllowTypes());
        map.put("max_size",storageConfig.getMaxSize());
        map.put("root_dir",storageConfig.getRootDir());
        map.put("ip_str",this.ip);
        return map;
    }

小 A 空间 , 版权所有丨如未注明转载 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Spring Boot2 学习笔记之获取配置参数(三)
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址