yml读取list对象_定义Configuration Processor读取spring配置

本文介绍了如何在Spring应用中使用Configuration Processor读取YAML配置文件。首先,需要引入maven依赖,并在YML配置文件中添加自定义配置。然后,创建一个@ConfigurationProperties注解的Java对象,匹配配置文件中的键值。通过配置处理器,可以自动将YAML配置映射到Java对象,方便直接在代码中使用。
摘要由CSDN通过智能技术生成
ca23ac0ec877530711a0cfcecdcdcacb.gif    阅读本文约需要6分钟 

大家好,我是你们的导师,我每天都会在这里给大家分享一些干货内容(当然了,周末也要允许老师休息一下哈)。上次老师跟大家分享了下分布式术语的相关知识,今天跟大家分享定义Configuration Processor读取spring配置的知识。

1 引入maven依赖

        <dependency>      <groupId>org.springframework.bootgroupId>      <artifactId>spring-boot-configuration-processorartifactId>      <optional>trueoptional>    dependency>

2 spring配置文件

在spring配置文件,xxx.properties或者xxx.yml中添加自定义配置(这里以yml为例)

test:  name: spring-boot-configuration-processor
3 创建一个自定义对象

创建一个自定义对象,名字叫什么随意,需要加上注解@ConfigurationProperties(prefix = "test"),这个test,对应着配置文件中的test,而属性name,则对应配置文件中的test下的name。

在这里,我使用了lombok,lombok 和 configuration-processor 是兼容的。

如果没有使用lombok,注意要加上getter和setter。

@Data@ConfigurationProperties(prefix = "test")public class TestModel {    private String name;}
4 注册对象的bean

在任意一个configuration文件中,注册这个对象的bean。

@SpringBootApplicationpublic class LeaningApplication {  @Bean  public TestModel testModel() {    return new TestModel();  }}
5 直接使用

直接使用即可。

@RestControllerpublic class HelloWorldController {    @Autowired    private TestModel testModel;    @GetMapping    public String hello() {        return testModel.getName();    }}
6 得到结果

得到结果:

MockHttpServletResponse:           Status = 200    Error message = null          Headers = {Content-Type=[application/json;charset=UTF-8], Content-Length=[35]}     Content type = application/json;charset=UTF-8             Body = spring-boot-configuration-processor    Forwarded URL = null   Redirected URL = null          Cookies = []
参考来源:https://my.oschina.net/anur/blog/1620579

今天就分享这么多,定义Configuration Processor读取spring配置,你会了多少欢迎在留言区评论,对于有价值的留言,我们都会一一回复的。如果觉得文章对你有一丢丢帮助,请点右下角【在看】,让更多人看到该文章。

04fe1db905082f53e26a9bd869df02f1.gif

0d5fb3bc1224589d2722f05c3b847c09.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值