日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot 之 Starter

發(fā)布時間:2023/12/20 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot 之 Starter 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、springboot Starter簡介

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

  • 它整合了這個模塊需要的依賴庫;
  • 提供對模塊的配置項給使用者、并可以對配置項提供默認值,使得使用者可以不指定配置時提供默認配置項值,也可以根據(jù)需要指定配置項值;
  • 提供自動配置類對模塊內(nèi)的Bean進行自動裝配
  • 例如,在Maven的依賴中加入spring-boot-starter-web就能使項目支持Spring MVC,并且Spring Boot還為我們做了很多默認配置,無需再依賴spring-web、spring-webmvc等相關(guān)包及做相關(guān)配置就能夠立即使用起來。

    官方提供的starter有50多種,見:Spring Boot Reference Guide

    二、Starter的開發(fā)步驟

  • 新建Maven項目,在項目的POM文件中定義使用的依賴;
  • 新建配置類,寫好配置項和默認的配置值,指明配置項前綴;
  • 新建自動裝配類,使用@Configuration和@Bean來進行自動裝配;
  • 新建spring.factories文件,指定Starter的自動裝配類;
  • 三、Starter的開發(fā)示例

    要想更好的理解springboot starter的作用,可以通過自定義一個Starter,在過程中進行理解。

    下面,我就以創(chuàng)建一個自動配置并連接ElasticSearch的Starter來講一下各個步驟及細節(jié)。

    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包。

    這里設置了x-pack-transport包的版本5.6.4

    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,各配置項均有默認值,默認值可以通過模塊使用者的配置文件進行覆蓋。

    • 通過@Data注解自動添加屬性的set/get方法
    • 通過@ConfigurationProperties(prefix ="sxw.elasticsearch")注解,關(guān)聯(lián)外部配置文件(application.yml或者application.properties)中以sxw.elasticsearch為前綴的配置項,如果設置時替換默認值
    • 默認值為聲明變量時同時給定的默認值

    3.新建自動裝配類(JavaConfig),使用@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;@Resourceprivate 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();}@Overridepublic void destroy() throws Exception {log.info("開始銷毀Es的連接");if (transportClient != null) {transportClient.close();}} }
    • 本類主要對TransportClient類進行自動配置;
    • 使用@ConditionalOnMissingBean注解:當Spring容器中沒有TransportClient類的對象時,調(diào)用transportClient()創(chuàng)建對象;

    關(guān)于更多Bean的條件裝配用法請自行查閱Spring Boot相關(guān)文檔;

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

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

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

    四.Starter的使用

    1.創(chuàng)建Maven項目,依賴剛才發(fā)布的es-starter包。

    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><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>

    只需依賴剛才開發(fā)的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根據(jù)類路徑中的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";@Autowiredprivate TransportClient transportClient;@Overridepublic 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("=======第一頁數(shù)據(jù):");for (SearchHit searchHit : hits) {Map<String, Object> source = searchHit.getSource();String question = source.get("question").toString();log.info(question);}} }
    • 通過實現(xiàn)ApplicationRunner或CommandLineRunner接口,可以實現(xiàn)應用程序啟動完成后自動運行run方法,達到測試es-starter模塊目的。
    • 索引名稱tb_question是公司測試環(huán)境ElasticSearch中的索引,已存在數(shù)據(jù)。

    4.應用程序配置

    sxw:elasticsearch:cluster-name: docker-clustercluster-nodes: 192.168.2.180:9300,192.168.2.181:9300user-name: elasticpassword: changeme

    5.運行程序測試

    /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/java "-javaagent:/Applications/開發(fā)/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=52434:/Applications/開發(fā)/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 : =======第一頁數(shù)據(jù): 2018-08-08 16:26:49.230 INFO 2017 --- [ main] c.s.c.data.es.example.ExampleRunner : <p>下列詩句朗讀節(jié)奏有錯誤的一項是( )</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:宋體,新宋體">該模式給當?shù)貛淼闹饕绊懯?</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條數(shù)據(jù)。

    源代碼參考提供:https://github.com/liushiping/examples/tree/master/es-spring-boot-starter

    博主github還有l(wèi)ucene、hbase等demo

    總結(jié)

    以上是生活随笔為你收集整理的springboot 之 Starter的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。