骚操作,创建自己的SpringBoot Starter

3,697 阅读11分钟

学 无 止 境 , 与 君 共 勉 。


自动配置

在SpringBoot中我们引用的很多包都是spring-boot-starter-XXX的格式。我们只需在Maven中引入starter依赖,SpringBoot就会自动注入需要的Bean,并进行默认配置,这是SpringBoot中的一种重要机制:自动配置。相比以前开发需要配置大量的XML文件,SpringBoot大大减少了开发人员的工作量。这些依赖都遵循着约定俗成的默认配置,同时允许我们调整这些配置,这就是我们通常讲的约定大于配置

应用场景

有时候在项目中我们需要集成第三方工具,比如极光推送,并且在多个项目中都需要用到。这就需要在每个项目中复制一份代码,重新集成,这造成了大量的重复工作,而且出了BUG修复时,每个项目都需要去修复一遍,增加工作量。这时我们就可以将这种业务封装成一个starter,需要用的时候直接在pom中引用依赖既可,比如:

  • 极光推送
  • 短信业务
  • 文件上传
  • 接口访问监控

自定义starter

一个完整的SpringBootStarter通常包含autoconfigurestarter两个模块,当然也可以将他们全都合并到starter模块中。

命名

官方命名:

  • spring-boot-starter-XXX
  • spring-boot-starter-jdbc
  • spring-boot-starter-data-redis

非官方命名:

  • XXX-spring-boot-starter
  • mybatis-spring-boot-starter
  • druid-spring-boot-starter

创建autoconfigure模块

该模块主要是我们的具体业务的实现,通常包含了:

  • 参数配置类(XXXProperties)
  • 具体业务实现类(需要被注入到容器的Bean)
  • 自动配置类(XXXAutoConfiguration)

创建一个Maven项目

这里我们类别选择maven-archetype-quickstar。t引入依赖:

    <!-- Spring Boot自身的自动配置 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>

创建参数类

参数类中设置了我们自定义starter中需要用到的配置,我们可以将其设置一个默认的值。比如redis的starter中的端口配置、连接池配置等。通过ConfigurationProperties注解,我们将properties或者yml文件中符合前缀的参数绑定到这个类的属性上

@ConfigurationProperties(prefix = "animal")
public class AnimalProperties {

    private String type = "animal";

    private String name;

    private final Fish fish = new Fish();

    private final bird bird = new bird();

    public static class Fish {

        private String doing;

        public String getDoing() {
            return doing;
        }

        public void setDoing(String doing) {
            this.doing = doing;
        }
    }

    public static class bird {

        private String doing;

        public String getDoing() {
            return doing;
        }

        public void setDoing(String doing) {
            this.doing = doing;
        }
    }

    //  省略get set 方法
}

这里属性的值我们可以在application.properties或者yml中来直接设置:

  • animal.name=XXX
  • animal.type=XXX
  • animal.bird.doing=XXX
  • animal.fish.doing=XXX

创建业务实现类

public class AnimalService {

    private AnimalProperties animalProperties;

    public AnimalService(AnimalProperties animalProperties) {
        this.animalProperties = animalProperties;
    }

    public void doing() {
        System.out.println("this is animal service");
        System.out.println("type:" + animalProperties.getType());
        System.out.println("name:" + animalProperties.getName());
    }

}

创建自动配置类

这是一个配置类,也是Spring直接扫描到的类,根据这个配置类的规则,满足条件的Bean将会被实例化到Spring容器中去

@Configuration
@EnableConfigurationProperties(AnimalProperties.class)
@ConditionalOnClass(AnimalProperties.class)
public class AnimalAutoConfiguration {

    @Autowired
    private AnimalProperties animalProperties;

    @Bean
    @ConditionalOnMissingBean(AnimalService.class)
    public AnimalService animalService() {
        return new AnimalService(animalProperties);
    }

}
  • @EnableConfigurationProperties表示启用@ConfigurationProperties注解,并将带有@ConfigurationProperties注解的Bean注入到容器中,这里将参数类AnimalProperties注入到容器中
  • @ConditionalOnClass(AnimalProperties.class)表示Classpath里有AnimalProperties这个类的时候才执行这个配置文件
  • @ConditionalOnMissingBean(AnimalService.class)表示容器中没有AnimalService这个Bean的时候才注入这个Bean

划重点:配置spring.factories

resources目录下新建META-INF目录,然后在META-INF目录下创建spring.factories文件,设置自动配置类的位置,若有多个配置类用”,”隔开即可。:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.ylc.note.demo.AnimalAutoConfiguration

Spring会扫描所有具有META-INF/spring.factories的jar包,加载factories中EnableAutoConfiguration对应的XxxxAutoConfiguration自动配置类,将满足条件的Bean注入到Sping容器中去。

如果没有resources这个文件夹的话需要自己建立,在idea中先建立一个directory,然后选中resources目录右键单击—》Mark Directory as—》Resource Root。

条件化配置

很多时候我们不需要将所有的Bean都实例化出来,只需要实例化满足了条件的Bean。在Spring4.0中引入了条件化配置这一新特性。我们可以通过实现Condition接口并重写matches方法来定义自己的条件化配置类。将配置类传入@Conditional(? extends Condition)注解来判断是否要实例化Bean,我们可以看下源码:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

    /**
     * 传入一个实现Condition接口的类
     */

    Class<? extends Condition>[] value();

}

public interface Condition {

    /**
     * 重写方法,只有当该方法返回true时才实例化Beab
     */

    boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}

实战一下

  • 重新定义一个业务类
public class BirdService {

    private AnimalProperties animalProperties;

    public BirdService(AnimalProperties animalProperties{
        this.animalProperties = animalProperties;
    }

    public void doing({
        System.out.println("this is bird service");
        System.out.println("type:" + animalProperties.getType());
        System.out.println("name:" + animalProperties.getName());
        System.out.println("doing:" + animalProperties.getBird().getDoing());
    }
}
  • 创建条件化配置类,只有配置了animal.bird.doing参数时才满足条件
public class BirdEnvironmentCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        String[] envs = env.getActiveProfiles();
        for (String e : envs) {
            System.out.println(e);
        }
        return env.containsProperty("animal.bird.doing");
    }

}
  • 扩展自动配置类,加入对BirdService的初始化,使用注解Conditional判断是否实例化Bean
@Configuration
@EnableConfigurationProperties(AnimalProperties.class)
@ConditionalOnClass(AnimalProperties.class)
public class AnimalAutoConfiguration {

    @Autowired
    private AnimalProperties animalProperties;

    @Bean
    @ConditionalOnMissingBean(AnimalService.class)
    public AnimalService animalService() {
        return new AnimalService(animalProperties);
    }

    /**
     * 只有满足当BirdEnvironmentCondition.matches 返回true时才实例化BirdService
     */

    @Bean
    @Conditional(BirdEnvironmentCondition.class)
    @ConditionalOnMissingBean(BirdService.class)
    public BirdService birdService() {
        return new BirdService(animalProperties);
    }

}

常用的条件化注解

条件化注解 配置生效条件
@ConditionalOnBean 配置了某个特定Bean
@ConditionalOnMissingBean 没有配置特定的Bean
@ConditionalOnClass Classpath里有指定的类
@ConditionalOnMissingClass Classpath里缺少指定的类
@ConditionalOnProperty 指定的配置属性要有一个明确的值
@ConditionalOnResource Classpath里有指定的资源
@ConditionalOnWebApplication 这是一个web应用
@ConditionalOnNotWebApplication 这不是一个web应用

创建starter模块

starter实际上是一个空的jar,它提供了对autoconfigure模块的依赖。它主要用来告知springBoot这个库需要哪些依赖,创建一个新模块,pom文件引入autoconfigure依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.ylc.note</groupId>
    <artifactId>common-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>common-spring-boot-starter</name>
    <description>common-spring-boot-starter</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- 引入autoconfigure -->
        <dependency>
            <groupId>org.ylc.note</groupId>
            <artifactId>common-spring-boot-autoconfigure</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

在项目中引用自定义的starter

新建一个SpringBoot项目,在pom中引入自定义starter

    <dependency>
        <groupId>org.ylc.note</groupId>
        <artifactId>common-spring-boot-starter</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

然后就可以在application.properties或者yml文件中配置相关的属性

代码自动提示

这时我们会发现在配置文件中设置参数时,不像Spring官方starter配置参数那样,有代码自动提示补全功能,而且还会提示无法解析配置属性的警告,但参数还是可以正常使用的。

spring-boot-configuration-processor

各位少侠莫慌,这是因为我们少了spring-configuration-metadata.json文件,它起到一个提示作用,需要在autoconfigure模块的resources/META-INF下创建这个文件。我们可以通过idea自动生成这个文件,需要在pom中引入依赖:

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

重新编译autoconfigure模块,然后配置参数的时候就有自动提示了。

如果还是不行,把autoconfigure模块在本地的jar包删掉,重新编译打包

spring-boot-autoconfigure-processor

还有一个jar包spring-boot-autoconfigure-processor建议也引入,编译打包后会在META-INF下自动生成spring-autoconfigure-metadata.properties文件,供AutoConfigurationImportSelector过滤加载,这里不具体展开。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure-processor</artifactId>
        <version>2.2.2.RELEASE</version>
        <optional>true</optional>
    </dependency>

创建测试接口

@RestController
@RequestMapping("/animal")
public class AnimalController {

    private final AnimalService animalService;

    private final BirdService birdService;

    public AnimalController(AnimalService animalService, BirdService birdService) {
        this.animalService = animalService;
        this.birdService = birdService;
    }

    @GetMapping("/")
    public String animal() {
        animalService.doing();
        return "animal";
    }

    @GetMapping("/bird")
    public String bird() {
        birdService.doing();
        return "bird";
    }
}

在properties或者yml文件配置参数

  • 在模块中,BirdService只有在参数存在animal.bird.doing配置时,才进行实例化,这里先不配置看看运行结果
animal.name=bird
animal.type=small animal

项目启动失败,提示没有这个类

Parameter 0 of constructor in org.ylc.note.commonspringboottest.controller.AnimalController required a bean of type 'org.ylc.note.demo.FishServicethat could not be found.
  • 配置animal.bird.doing
animal.name=bird
animal.type=small animal
animal.bird.doing=flying

启动成功

访问http://localhost:8080/animal/

this is animal service
type:small animal
name:bird

访问http://localhost:8080/animal/

this is bird service
type:small animal
name:bird
doing:flying

AnimalService和BirdService都成功实例化

访问源码

所有代码均上传至Github上,方便大家访问,并包含了对极光推送的封装

>>>>>> 自定义starter <<<<<<

日常求赞

创作不易,如果各位觉得有帮助,求点赞支持

求关注

微信公众号: 俞大仙