使用@ConfigurationProperties注解读取配置文件

配置样例

application.yaml内容如下:

#系统配置
sys:
  web-title: 网站标题
  web-seo: 网站优化

#上传配置
upload:
  max-size: 最大上传文件
  ext: 文件后缀

读取配置

定义javaBean(配置组件)

上传配置组件:新建一个Sys类

package com.yfway.demo.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sys")
@Data
public class Sys {
    private String webTitle;
    private String webSeo;
}

@ConfigurationProperties注解就是将配置文件的属性值映射到当前类中

prefix = "sys":配置文件中哪个下面的所有属性进行一一映射

注意属性映射支持松散语法,例如webTitle->web-title

上传配置也可以新建一个组件,这里就不再重复讲述

调用配置组件

@Autowired
Sys sys;

@Test
public void test(){
    System.out.print(sys.getWebTitle());
    System.out.print(sys.getWebSeo());
}

扩展

@ConfigurationProperties支持JSR303数据校验

@Component
@ConfigurationProperties(prefix = "sys")
@Data
@Validated
public class Sys {
    @NotBlank(message = "名称不能为空")
    private String webTitle;
    private String webSeo;
}

如果配置文件的web-title值不存在的话,就会报错

@ConfigurationProperties支持复杂的数据类型

例如属性的值是个List 、Set集合,对象、Map等

配置提示

可以导入配置文件处理器,以后编写配置就有提示了


    org.springframework.boot
    spring-boot-configuration-processor
    true
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章