starter原理

举一个spring-boot-starter-web的例子
项目中依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

再看下spring-boot-starter-web的pom

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.1.6.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-json</artifactId>
      <version>2.1.6.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.1.6.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.17.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.1.8.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.8.RELEASE</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

等于说:spring-boot-starter-web项目中是什么都没有的,只是在pom中提供了一些快速开发所需要的依赖。而真正注入的类都是在其他的依赖中。
比如spring-boot-starter-json项目也是什么都没有的,但它引入了JACKSON

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jdk8</artifactId>
      <version>2.9.9</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.9.9</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
      <version>2.9.9</version>
      <scope>compile</scope>
    </dependency>

当我们的项目引入了JACKSON,SPRINGBOOT就能够自动注入该配置下符合要求的BEAN(如下的ObjectMapper.class就是jackson-databind中的一个类)

@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration 

此外还可以直接在application.yml配置文件直接定制自动注入的BEAN

@ConfigurationProperties(prefix = "spring.jackson")
public class JacksonProperties

根据springboot自带的autoconfigure和starter项目,我们可以照葫芦画瓢的定制我们自己的starter。