当前位置:   article > 正文

如何做一个springboot的starter类型的SDK

如何做一个springboot的starter类型的SDK

关键的东西

首先我们是一个starter类型的SDK,为了给调用者使用,其中有一些Bean我们会放到SDK中,并且这些Bean能够注入到调用者的Spring容器中。

最关键的spring.factories文件

这个文件所在位置如下图所示,该文件通过写入一下代码,可以将我们的Bean注入到调用者的Spring容器中。 如下所示有两个

  1. com.example.demo0415starter.config.MyConfig 这个配置类
  2. com.example.demo0415starter.config.InterceptorConfig 这个配置类
    这两个配置类都是@Configuration标注的,当然 你也可以写@Component 都一样。
org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.example.demo0415starter.config.MyConfig,com.example.demo0415starter.config.InterceptorConfig
  • 1

在这里插入图片描述

读取调用者的配置文件

我们使用jdbc-starter时,在我们的yml文件中需要配置里面的 driver、ip、host等数据。
那么我们的starter-SDK如何读取调用者的配置呢?
答:@ConfigurationProperties
被该注解标注的对象是一个配置对象,该对象中的属性 与 yml文件一一对应

@ConfigurationProperties(prefix = "person")
public class PersonProperties {

    private String name;
    private int age;
    private boolean married;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

PersonProperties作为一个配置对象,对象!对象!。那么他也要注入到Spring容器中才行。

那么我们有2种方式

  1. 使用spring.factories文件直接导入 com.xxx.xxx.xxx.PersonProperties。
  2. 使用@EnableConfigurationProperties(PersonProperties.class)注解
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/458287
推荐阅读
相关标签
  

闽ICP备14008679号