從零開始開發一個Spring Boot Starter

一.Spring Boot Starter簡介

Starter是Spring Boot中的一個非常重要的概念,Starter相當于模塊,它能將模塊所需的依賴整合起來并對模塊內的Bean根據環境( 條件)進行自動配置。使用者只需要依賴相應功能的Starter,無需做過多的配置和依賴,Spring Boot就能自動掃描并加載相應的模塊。
總結:

1.它整合了這個模塊需要的依賴庫;
2.提供對模塊的配置項給使用者;
3.提供自動配置類對模塊內的Bean進行自動裝配;

例如,在Maven的依賴中加入spring-boot-starter-web就能使項目支持Spring MVC,并且Spring Boot還為我們做了很多默認配置,無需再依賴spring-web、spring-webmvc等相關包及做相關配置就能夠立即使用起來。

二.Starter的開發步驟

編寫Starter非常簡單,與編寫一個普通的Spring Boot應用沒有太大區別,總結如下:

1.新建Maven項目,在項目的POM文件中定義使用的依賴;
2.新建配置類,寫好配置項和默認的配置值,指明配置項前綴;
3.新建自動裝配類,使用@Configuration和@Bean來進行自動裝配;
4.新建spring.factories文件,指定Starter的自動裝配類;

三.Starter的開發示例

下面,我就以創建一個自動配置并連接ElasticSearch的Starter來講一下各個步驟及細節。
1.新建Maven項目,在項目的POM文件中定義使用的依賴。

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.4.RELEASE</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>es-starter</artifactId>
        <version>1.0.0.SNAPSHORT</version>
    
        <dependencies>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.18</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <version>2.0.4.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>x-pack-transport</artifactId>
                <version>5.6.4</version>
            </dependency>
        </dependencies>
    </project>

由于本starter主要是與ElasticSearch建立連接,獲得TransportClient對象,所以需要依賴x-pack-transport包。

2.新建配置類,寫好配置項和默認的配置值,指明配置項前綴。

package cn.sxw.commons.data.es.starter;

import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Data;

/**
 * Created by William on 2018/8/7.
 */
@Data
@ConfigurationProperties(prefix = "sxw.elasticsearch")
public class ElasticSearchProperties {

    private String clusterName = "elasticsearch";

    private String clusterNodes = "127.0.0.1:9300";

    private String userName = "elastic";

    private String password = "changeme";

}

指定配置項前綴為sxw.elasticsearch,各配置項均有默認值,默認值可以通過模塊使用者的配置文件進行覆蓋。

3.新建自動裝配類,使用@Configuration@Bean來進行自動裝配。

package cn.sxw.commons.data.es.starter;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by William on 2018/8/7.
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ElasticSearchProperties.class)
public class ElasticSearchAutoConfiguration implements DisposableBean{

    private TransportClient transportClient;
    @Resource
    private ElasticSearchProperties properties;

    @Bean
    @ConditionalOnMissingBean(TransportClient.class)
    public TransportClient transportClient() {
        log.debug("=======" + properties.getClusterName());
        log.debug("=======" + properties.getClusterNodes());
        log.debug("=======" + properties.getUserName());
        log.debug("=======" + properties.getPassword());
        log.info("開始建立es連接");
        transportClient = new PreBuiltXPackTransportClient(settings());
        TransportAddress[] transportAddresses= Arrays.stream(properties.getClusterNodes().split(",")).map (t->{
            String[] addressPortPairs = t.split(":");
            String address = addressPortPairs[0];
            Integer port = Integer.valueOf(addressPortPairs[1]);
            try {
                return new InetSocketTransportAddress(InetAddress.getByName(address), port);
            } catch (UnknownHostException e) {
                log.error("連接ElasticSearch失敗", e);
                throw new RuntimeException ("連接ElasticSearch失敗",e);
            }
        }).collect (Collectors.toList ()).toArray (new TransportAddress[0]);
        transportClient.addTransportAddresses(transportAddresses);
        return transportClient;
    }

    private Settings settings() {
        return Settings.builder()
                .put("cluster.name", properties.getClusterName())
                .put("xpack.security.user", properties.getUserName() +
                        ":" + properties.getPassword())
                .build();
    }

    @Override
    public void destroy() throws Exception {
        log.info("開始銷毀Es的連接");
        if (transportClient != null) {
            transportClient.close();
        }
    }
}

本類主要對TransportClient類進行自動配置;
@ConditionalOnMissingBean 當Spring容器中沒有TransportClient類的對象時,調用transportClient()創建對象;
關于更多Bean的條件裝配用法請自行查閱Spring Boot相關文檔;

4.新建spring.factories文件,指定Starter的自動裝配類。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  cn.sxw.commons.data.es.starter.ElasticSearchAutoConfiguration

spring.factories文件位于resources/META-INF目錄下,需要手動創建;
org.springframework.boot.autoconfigure.EnableAutoConfiguration后面的類名說明了自動裝配類,如果有多個 ,則用逗號分開;
使用者應用(SpringBoot)在啟動的時候,會通過org.springframework.core.io.support.SpringFactoriesLoader讀取classpath下每個Starter的spring.factories文件,加載自動裝配類進行Bean的自動裝配;

至此,整個Starter開發完畢,Deploy到中央倉庫或Install到本地倉庫后即可使用。

四.Starter的使用

1.創建Maven項目,依賴剛才發布的es-starter包。

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-boot-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>es-example</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>es-starter</artifactId>
            <version>1.0.0.SNAPSHORT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

只需依賴剛才開發的es-starter即可

2.編寫應用程序啟動類。

package cn.sxw.commons.data.es.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by William on 2018/8/7.
 */
@SpringBootApplication
@ComponentScan("cn.sxw.commons.data.es.example")
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

@SpringBootApplication由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三個注解組合而成,其中@EnableAutoConfiguration注解讓Spring Boot根據類路徑中的jar包依賴為當前項目進行自動配置。

3.編寫查詢ElasticSearch的使用類

package cn.sxw.commons.data.es.example;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by William on 2018/8/7.
 */
@Slf4j
@Component
public class ExampleRunner implements ApplicationRunner {

    private static final String INDEX_NAME = "tb_question";

    @Autowired
    private TransportClient transportClient;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        SearchResponse response = transportClient.prepareSearch(INDEX_NAME)
                .setTypes(INDEX_NAME)
                .setQuery(QueryBuilders.matchAllQuery())
                .setFrom(0).setSize(5).execute().actionGet();
        SearchHits hits = response.getHits();
        log.info(String.format("=======總共找到%d條記錄", hits.getTotalHits()));
        log.info("=======第一頁數據:");
        for (SearchHit searchHit : hits) {
            Map<String, Object> source = searchHit.getSource();
            String question = source.get("question").toString();
            log.info(question);
        }
    }
}

通過實現ApplicationRunner或CommandLineRunner接口,可以實現應用程序啟動完成后自動運行run方法,達到測試es-starter模塊目的。
索引名稱tb_question是公司測試環境ElasticSearch中的索引,已存在數據。

4.應用程序配置

sxw:
  elasticsearch:
    cluster-name: docker-cluster
    cluster-nodes: 192.168.2.180:9300,192.168.2.181:9300
    user-name: elastic
    password: changeme

在application.yml文件中配置es-starter需要的配置信息,這里連接公司測試環境中的ElasticSearch。
這里配置的值可以覆蓋es-starter中默認值,也就是之前ElasticSearchProperties文件中的默認值。

5.運行程序測試

/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/java "-javaagent:/Applications/開發/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=52434:/Applications/開發/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath cn.sxw.commons.data.es.example.ExampleApplication
objc[2017]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/java (0x1022a24c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1023254e0). One of the two will be used. Which one is undefined.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.4.RELEASE)

2018-08-08 16:26:43.161  INFO 2017 --- [           main] c.s.c.d.es.example.ExampleApplication    : Starting ExampleApplication on William.local with PID 2017 (/Users/William/Git/sxw-java/es-spring-boot-starter/es-example/target/classes started by William in /Users/William/Git/sxw-java/es-spring-boot-starter)
2018-08-08 16:26:43.167  INFO 2017 --- [           main] c.s.c.d.es.example.ExampleApplication    : No active profile set, falling back to default profiles: default
2018-08-08 16:26:43.365  INFO 2017 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@635eaaf1: startup date [Wed Aug 08 16:26:43 CST 2018]; root of context hierarchy
2018-08-08 16:26:45.078  INFO 2017 --- [           main] s.c.d.e.s.ElasticSearchAutoConfiguration : =======docker-cluster
2018-08-08 16:26:45.079  INFO 2017 --- [           main] s.c.d.e.s.ElasticSearchAutoConfiguration : =======192.168.2.180:9300,192.168.2.181:9300
2018-08-08 16:26:45.081  INFO 2017 --- [           main] s.c.d.e.s.ElasticSearchAutoConfiguration : =======elastic
2018-08-08 16:26:45.081  INFO 2017 --- [           main] s.c.d.e.s.ElasticSearchAutoConfiguration : =======changeme
2018-08-08 16:26:45.082  INFO 2017 --- [           main] s.c.d.e.s.ElasticSearchAutoConfiguration : 開始建立es連接
2018-08-08 16:26:46.200  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : no modules loaded
2018-08-08 16:26:46.201  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]
2018-08-08 16:26:46.202  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.join.ParentJoinPlugin]
2018-08-08 16:26:46.202  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]
2018-08-08 16:26:46.202  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]
2018-08-08 16:26:46.202  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.transport.Netty3Plugin]
2018-08-08 16:26:46.202  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.transport.Netty4Plugin]
2018-08-08 16:26:46.202  INFO 2017 --- [           main] o.elasticsearch.plugins.PluginsService   : loaded plugin [org.elasticsearch.xpack.XPackPlugin]
2018-08-08 16:26:49.137  INFO 2017 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-08-08 16:26:49.157  INFO 2017 --- [           main] c.s.c.d.es.example.ExampleApplication    : Started ExampleApplication in 6.6 seconds (JVM running for 7.915)
2018-08-08 16:26:49.215  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : =======總共找到907條記錄
2018-08-08 16:26:49.215  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : =======第一頁數據:
2018-08-08 16:26:49.230  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : <p>下列詩句朗讀節奏有錯誤的一項是(  )</p>
2018-08-08 16:26:49.230  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : <p><span style=";font-family:宋體;color:rgb(0,0,0);font-size:14px"><span style="font-family:宋體">《臥薪嘗膽》這個故事出自于(</span> A &nbsp;&nbsp;<span style="font-family:宋體">)</span></span></p><p><span style=";font-family:宋體;color:rgb(0,0,0);font-size:14px">A<span style="font-family:宋體">、司馬遷《史記》 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family:Times New Roman">B</span><span style="font-family:宋體">、司馬光 《資治通鑒》</span></span></p><p><span style=";font-family:宋體;color:rgb(0,0,0);font-size:14px">C<span style="font-family:宋體">、孔子 &nbsp;&nbsp;《論語》 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family:Times New Roman">D</span><span style="font-family:宋體">、司馬遷《春秋》</span></span></p><p><br/></p>
2018-08-08 16:26:49.230  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : <p style="margin-bottom:7px;margin-bottom:auto;vertical-align:middle"><span style=";font-family:&#39;Cambria Math&#39;;font-size:14pxfont-family:宋體,新宋體">填空題</span></p><p style="margin-bottom:7px;margin-bottom:auto;vertical-align:middle"><span style=";font-family:&#39;Cambria Math&#39;;font-size:14pxfont-family:宋體,新宋體">該模式給當地帶來的主要影響是 </span><span style=";font-family:&#39;Cambria Math&#39;;font-size:14px"><br/></span><br/></p><p><br/></p>
2018-08-08 16:26:49.231  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : <p>下列詞語沒有錯別字的一項是(  )</p>
2018-08-08 16:26:49.231  INFO 2017 --- [           main] c.s.c.data.es.example.ExampleRunner      : <p>語文第16題</p>
2018-08-08 16:26:49.232  INFO 2017 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@635eaaf1: startup date [Wed Aug 08 16:26:43 CST 2018]; root of context hierarchy
2018-08-08 16:26:49.234  INFO 2017 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2018-08-08 16:26:49.328  INFO 2017 --- [       Thread-2] s.c.d.e.s.ElasticSearchAutoConfiguration : 開始銷毀Es的連接

Process finished with exit code 0

運行程序,觀察控制臺輸出,es-starter成功與ElasticSearch建立連接,且應用程序啟動完后ExampleRunner的run方法查詢出5條數據。

源代碼參考提供:
從零開始開發一個Spring Boot Starter

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容