Springboot 搭建自己的starter

406 阅读2分钟

在我们使用SpringBoot starter的时候,比如MyBatis,我们只需要引入MyBatis相关的starter即可,然后配置文件中写好配置就行,以前我们需要配置MyBatis的配置文件,还有各种各样的配置,这样就简单多了

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
</dependency>

1:既然starter这么好用,那么我们自己也动手搭建一个吧,首先创建一个SpringBoot项目,pom.xml文件引入一个依赖

  SpringBoot版本我是用的2.2.2版本的
  
  <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-autoconfigure</artifactId>
  </dependency>
  

2:编写属性源

 /**
 * 读取属性源,读取前缀为coco的配置
 */
@ConfigurationProperties(prefix = "coco")
public class StarterSource {

    /**
     * 定义二个属性,到时候配置文件直接写 coco.type=123
     *                                 coco.rate=123
     */
    private String type;
    private String rate;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getRate() {
        return rate;
    }

    public void setRate(String rate) {
        this.rate = rate;
    }
}

3:编写服务类,给外界提供接口服务的

 /**
 * 给外部提供接口使用
 */
public class StartService {

    private StarterSource starterSource;

    public StartService(StarterSource starterSource) {
        this.starterSource = starterSource;
    }

    /**
     * 提供二个方法让外界获取这二个属性值
     * @return
     */
    public String getType() {
        return starterSource.getType();
    }

    public String getRate() {
        return starterSource.getRate();
    }
}

4:编写属性自动配置类

   /**
   * 属性自动配置类
   */
  @Configuration
  @EnableConfigurationProperties(StarterSource.class)
  /**
   * 存在配置 weather.enable 并且它的值要是 enable,这个配置类才有效
   */
  @ConditionalOnProperty(name = "weather.enable",havingValue = "enable")
  public class StarterAutoConfiguration {

      @Autowired
      private StarterSource starterSource;

      @Bean
      /**
       * 当用户没有自己实现该服务的实例才会实例这个Bean
       */
      @ConditionalOnMissingBean(StartService.class)
      public StartService startService() {
          return new StartService(starterSource);
      }
  }
  

5:在spring.factories文件添加自动配置类的实现,在resource目录下创建一个META-INF的文件夹,文件夹里面创建一个spring.factories的文件,文件内容如下

//配置我们自己的属性自动配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.starter.StarterAutoConfiguration

6:安装一个maven help的插件,插件安装好之后,右键项目 Run Maven-> clean install,编译成功之后到另外一个SpringBoot项目中引入这个依赖

7:准备测试:

//在application.properties配置下面三个属性
coco.type=java
coco.rate=spark
//这个配置一定要的,至于为什么可以看第4步
weather.enable=enable

新建一个Controller

@Autowired
private StartService startService;

@GetMapping("/test")
public String test() {
	return startService.getType();
}

8:浏览器输入localhost:8080/test 就可以看到输出java了,因为我们配置type的值就是java