定义一个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配置文件,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 = []

猜你喜欢

转载自blog.csdn.net/anurnomeru/article/details/79621783
今日推荐