定义Configuration Processor读取spring配置

1 引入maven依赖

   <!-- configuration-processor -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </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。

@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 = []

参考来源:https://my.oschina.net/anur/blog/1620579

发布了90 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_20282955/article/details/104243726
今日推荐