SpringBoot starter机制

1,828 阅读3分钟

      SpringBoot中的starter是一种非常重要的机制,能够抛弃以前繁杂的配置,将其统一集成进starter,应用者只需要在maven中引入starter依赖,SpringBoot就能自动扫描到要加载的信息并启动相应的默认配置。starter让我们摆脱了各种依赖库的处理,需要配置各种信息的困扰。SpringBoot会自动通过classpath路径下的类发现需要的Bean,并注册进IOC容器。SpringBoot提供了针对日常企业应用研发各种场景的spring-boot-starter依赖模块。所有这些依赖模块都遵循着约定成俗的默认配置,并允许我们调整这些配置,即遵循“约定大于配置”的理念。

      比如我们在springboot里面要引入redis,那么我们需要在pom中引入以下内容

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

     这其实就是一个starter。简而言之,starter就是一个外部的项目,我们需要使用它的时候就可以在当前springboot项目中引入它。

     在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的包下,然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一遍,麻烦至极。如果我们将这些可独立于业务代码之外的功配置模块封装成一个个starter,复用的时候只需要将其在pom中引用依赖即可,再由springBoot为我们完成自动装配,就非常轻松了

自定义starter的命名规则

     SpringBoot提供的starter以spring-boot-starter-xxx 的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter 命名规则。以区分SpringBoot生态提供的starter

自定义starter代码实现

整个过程分为两部分:

自定义starter

首先,先完成自定义starter (1)新建maven jar工程,工程名为zdy-spring-boot-starter,导入依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>2.2.9.RELEASE</version>
    </dependency>
</dependencies>

(2)编写javaBean

@EnableConfigurationProperties(SimpleBean.class)
@ConfigurationProperties(prefix = "simplebean")
public class SimpleBean {
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "SimpleBean{" + "id=" + id +'}';
    }
}

(3)编写配置类MyAutoConfiguration

@Configuration
public class MyAutoConfiguration {
    static {
        System.out.println("MyAutoConfiguration init....");
    }
    @Bean
    public SimpleBean simpleBean(){
        return new SimpleBean();
    }
}

(4)resources下创建/META-INF/spring.factories 注意:META-INF是自己手动创建的目录,spring.factories也是手动创建的文件,在该文件中配置自己的自动配置类。SpringBoot启动的时候会去加载我们的simpleBean到IOC容器中。这其实 是一种变形的SPI机制

使用starter

(1)导入自定义starter的依赖

<dependency>
    <groupId>com.lagou</groupId>
    <artifactId>zdy-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

(2)在全局配置文件中配置属性值

simplebean.id=1
simplebean.name=自定义starter

(3)编写测试方法

//测试自定义starter
@Autowired
private SimpleBean simpleBean;
@Test
public void zdyStarterTest(){
    System.out.println(simpleBean);
}

热插拔技术

在启动类Application上面加@EnableXXX注解,@Enablexxx注解就是一种热拔插技术,加了这个注解就可以启动对应的starter,当不需要对应的starter的时候只需要把这个注解注释掉就行