Spring boot starter原理,手?jǐn)]一個(gè)starter

  1. 什么是starter?

    starter是SpringBoot中的一個(gè)新發(fā)明,它有效的降低了項(xiàng)目開發(fā)過程的復(fù)雜程度,對于簡化開發(fā)操作有著非常好的效果。提供一個(gè)開箱即用的組件。

  2. 手寫一個(gè)starter

    假設(shè)我們有個(gè)需求,我們需要序列化一個(gè)對象,當(dāng)工程中存在FastJson的com.alibaba.fastjson.JSON類時(shí)使用FastJson序列化,如果不存在就則進(jìn)行簡單的toString操作。

    我們首先定義一個(gè)接口有一個(gè)格式化方法

    public interface FormatProcessor {
        //定義一個(gè)序列化的方法
        <T> String format(T obj);
    }
    

    然后這個(gè)接口有兩個(gè)實(shí)現(xiàn)類,分別做不同序列化操作。

    import com.alibaba.fastjson.JSON;
    
    public class JsonFormatProcessor implements FormatProcessor{
        @Override
        public <T> String format(T obj) {
            return "JsonFormatProcessor:"+ JSON.toJSONString(obj);
        }
    }
    
    import java.util.Objects;
    
    public class StringFormatProcessor implements FormatProcessor{
    
    
        @Override
        public <T> String format(T obj) {
            return "StringFormatProcessor:"+Objects.toString(obj);
        }
    }
    

    定義一個(gè)Configuration類。

    @Configuration
    public class FormatAutoConfiguration {
        @ConditionalOnMissingClass("com.alibaba.fastjson.JSON") // 如果不存在JSON類就加載
        @Bean
        @Primary //  如果有兩個(gè)實(shí)現(xiàn)則優(yōu)先加載這個(gè)
        public FormatProcessor stringFormat() {
            return new StringFormatProcessor();
        }
    
        @ConditionalOnClass(name = "com.alibaba.fastjson.JSON") // 如果存在JSON類
        @Bean
        public FormatProcessor jsonFormat() {
            return new JsonFormatProcessor();
        }
    }
    

    定義一個(gè)自動配置類。

    @Import(FormatAutoConfiguration.class)
    @Configuration
    public class HelloAutoConfiguration {
    
        @Bean
        public HelloFormatTemplate helloFormatTemplate( FormatProcessor formatProcessor) {
            return new HelloFormatTemplate(formatProcessor);
        }
    }
    

    template類

    public class HelloFormatTemplate {
    
        private FormatProcessor formatProcessor;
    
        public HelloFormatTemplate(FormatProcessor formatProcessor) {
            this.formatProcessor = formatProcessor;
        }
    
        public <T> String doFormat(T obj){
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append("begin:Execute format").append("<br/>");
            stringBuilder.append("Obj format result:").append(formatProcessor.format(obj)).append("<br/>");
            return stringBuilder.toString();
        }
    }
    

    使用spring boot的SPI機(jī)制把 HelloAutoConfiguration自動裝配進(jìn)spring容器。在spring.factories文件中定義

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      com.yhx.starter.autoconfiguration.HelloAutoConfiguration
    

    這樣我們就寫出了一個(gè)starter,實(shí)現(xiàn)了一個(gè)類似以RedisTemplate的HelloFormatTemplate的工具。那如果我們要使用外部化的配置也就要讀取到application.yml文件的配置該怎么寫呢?

    首先我們寫一個(gè)Properties類,并加上@ConfigurationProperties注解。

    @ConfigurationProperties(prefix = HelloProperties.HELLO_FORMAT_PREFIX)
    public class HelloProperties {
        public static final String HELLO_FORMAT_PREFIX = "yhx.hello.format";
        private Map<String, Object> info;
        public Map<String, Object> getInfo() {
            return info;
        }
        public void setInfo(Map<String, Object> info) {
            this.info = info;
        }
    }
    

    然后在HelloAutoConfiguration的自動裝配的類中加上@EnableConfigurationProperties(HelloProperties.class),此時(shí)HelloAutoConfiguration類為

    @Import(FormatAutoConfiguration.class)
    @EnableConfigurationProperties(HelloProperties.class)
    @Configuration
    public class HelloAutoConfiguration {
    
        @Bean
      // HelloProperties這時(shí)候的已經(jīng)在spring容器中了,會自動去找查的
        public HelloFormatTemplate helloFormatTemplate(HelloProperties helloProperties, FormatProcessor formatProcessor) {  
            return new HelloFormatTemplate(helloProperties, formatProcessor);
        }
    }
    

    這時(shí)候我們的Template可以改寫為如下的

    public class HelloFormatTemplate {
    
        private FormatProcessor formatProcessor;
    
        private HelloProperties helloProperties;
    
        public HelloFormatTemplate(HelloProperties helloProperties,FormatProcessor formatProcessor) {
            this.helloProperties=helloProperties;
            this.formatProcessor = formatProcessor;
        }
    
        public <T> String doFormat(T obj){
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append("begin:Execute format").append("<br/>");
           stringBuilder.append("HelloProperties:").append(formatProcessor.format(helloProperties.getInfo())).append("<br/>");
            stringBuilder.append("Obj format result:").append(formatProcessor.format(obj)).append("<br/>");
            return stringBuilder.toString();
    
        }
    }
    

    我們在使用這個(gè)這個(gè)starter的工程中在application.yml或者是application.properties中配置,就可以配置進(jìn)這個(gè)序列化的bean中

    yhx.hello.format.info.country=CN
    yhx.hello.format.info.provice=HuNan
    yhx.hello.format.info.city=shanghai
    yhx.hello.format.info.org=xingren
    
  3. 常見的starter之logger

    我們在項(xiàng)目中加入logging starter的依賴

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
        <version>2.3.4.RELEASE</version>
    </dependency>
    

    然后看一下spring-boot-starter-logging的jar包,發(fā)現(xiàn)里面并沒有什么,這是為什么呢?

    spring-boot-starter-logging-2.3.4.RELEASE.jar
     META-INF
         LICENSE.txt
         MANIFEST.MF
         NOTICE.txt
    

    然后我們點(diǎn)進(jìn)pom文件中的spring-boot-starter-logging看看

    <?xml version="1.0" encoding="UTF-8"?>
    <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <!-- This module was also published with a richer model, Gradle metadata,  -->
      <!-- which should be used instead. Do not delete the following line which  -->
      <!-- is to indicate to Gradle or any Gradle module metadata file consumer  -->
      <!-- that they should prefer consuming it instead. -->
      <!-- do_not_remove: published-with-gradle-metadata -->
      <modelVersion>4.0.0</modelVersion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
      <version>2.3.4.RELEASE</version>
      <name>spring-boot-starter-logging</name>
      <description>Starter for logging using Logback. Default logging starter</description>
      <url>https://spring.io/projects/spring-boot</url>
      <organization>
        <name>Pivotal Software, Inc.</name>
        <url>https://spring.io</url>
      </organization>
      <licenses>
        <license>
          <name>Apache License, Version 2.0</name>
          <url>https://www.apache.org/licenses/LICENSE-2.0</url>
        </license>
      </licenses>
      <developers>
        <developer>
          <name>Pivotal</name>
          <email>info@pivotal.io</email>
          <organization>Pivotal Software, Inc.</organization>
          <organizationUrl>https://www.spring.io</organizationUrl>
        </developer>
      </developers>
      <scm>
        <connection>scm:git:git://github.com/spring-projects/spring-boot.git</connection>
        <developerConnection>scm:git:ssh://git@github.com/spring-projects/spring-boot.git</developerConnection>
        <url>https://github.com/spring-projects/spring-boot</url>
      </scm>
      <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/spring-projects/spring-boot/issues</url>
      </issueManagement>
      <dependencies>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.2.3</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-to-slf4j</artifactId>
          <version>2.13.3</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>jul-to-slf4j</artifactId>
          <version>1.7.30</version>
          <scope>compile</scope>
        </dependency>
      </dependencies>
    </project>
    
    

    里面就是一堆依賴,為什么空的也能實(shí)現(xiàn)自動裝配呢?因?yàn)閟pring boot官方提供了裝配,如果相關(guān)的類或者一類存在的話,所以logging的starter只需要添加一些依賴就可以。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容