SpringBoot读取配置信息

配置文件:

#服务端口号
server:
  port: 8081

app:
  proper:
    key: ${random.uuid}
    id: ${random.int}
    value: test123

  demo:
    val: autoInject

1.Environment 读取

使用方式:

@RestController
public class DemoController {
    @Autowired
    private Environment environment;

    @GetMapping(path = "show")
    public String show() {
        Map<String, String> result = new HashMap<>(4);
        result.put("env", environment.getProperty("server.port"));
        return JSON.toJSONString(result);
    }
}

2.@Value 注解方式
@Value注解可以将配置信息注入到Bean的属性,也是比较常见的使用方式,但有几点需要额外注意

如果配置信息不存在会怎样?
配置冲突了会怎样(即多个配置文件中有同一个key时)?
使用方式如下,主要是通过 ${},大括号内为配置的Key;
如果配置不存在时,给一个默认值时,可以用冒号分割,后面为具体的值

@RestController
public class DemoController {
    // 配置必须存在,且获取的是配置名为 app.demo.val 的配置信息
    @Value("${app.demo.val}")
    private String autoInject;

    // 配置app.demo.not不存在时,不抛异常,给一个默认值data
    @Value("${app.demo.not:dada}")
    private String notExists;

    @GetMapping(path = "show")
    public String show() {
        Map<String, String> result = new HashMap<>(4);
        result.put("autoInject", autoInject);
        result.put("not", notExists);
        return JSON.toJSONString(result);
    }
}

3.对象映射方式

即通过注解ConfigurationProperties来制定配置的前缀
通过Bean的属性名,补上前缀,来完整定位配置信息的Key,并获取Value赋值给这个Bean
上面这个过程,配置的注入,从有限的经验来看,多半是反射来实现的,所以这个Bean属性的Getter/Setter方法得加一下,上面借助了Lombok来实现,标一个@Component表示这是个Bean,托付给Spring的ApplicationConttext来管理
如下:

@Data
@Component
@ConfigurationProperties(prefix = "app.proper")
public class ProperBean {
    private String key;
    private Integer id;
    private String value;
}

扩展:
properties配置优先级 > YAML配置优先级

原文地址:https://www.cnblogs.com/snail-gao/p/11865402.html