SpringBoot读取配置信息

配置文件:java

#服务端口号
server:
  port: 8081

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

  demo:
    val: autoInject

1.Environment 读取app

使用方式:dom

@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的属性,也是比较常见的使用方式,但有几点须要额外注意ui

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

@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.对象映射方式server

即经过注解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配置优先级get

相关文章
相关标签/搜索