定义一个Configuration Processor读取spring配置!

3 篇文章 0 订阅

1、引入maven依赖

        <!-- configuration-processor -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2、在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、在任意一个configuration文件中,注册这个对象的bean。

@SpringBootApplication
public class LeaningApplication {
    @Bean
    public TestModel testModel() {
        return new TestModel();
    }
}

5、直接使用即可。

@RestController
public 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 = []
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值