一、码前必备知识

1.1、SpringBoot starter机制

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

1.2、为什么要自定义starter

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

1.3、自定义starter的案例

以下案例由笔者工作中遇到的部分场景

  ▲ 动态数据源。

  ▲ 登录模块。

  ▲ 基于AOP技术实现日志切面。

  。。。。。。

1.4、自定义starter的命名规则

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

1.5、代码地址

https://gitee.com/qianwx/web-starter.git

二、starter的实现方法

2.1 新建一个工程

命名项目web-starter;

总项目结构及文件:

2.2 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"><modelVersion>4.0.0</modelVersion><groupId>com.qian</groupId><artifactId>web-starter</artifactId><version>1.0-SNAPSHOT</version><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>8</source><target>8</target></configuration></plugin></plugins></build><dependencies><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.3.0.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.12</version></dependency><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.16</version><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.30</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-web --><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.2.6.RELEASE</version></dependency><!--非必需,该依赖作用是在使用IDEA编写配置文件有代码提示--><dependency><groupId>org.springframework.boot</groupId><artifactId>r</artifactId><version>2.1.3.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><version>2.3.0.RELEASE</version><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency></dependencies>
</project>

2.3 定义一个实体类映射配置信息

@ConfigurationProperties(prefix = "demo") 它可以把相同前缀的配置信息通过配置项名称映射成实体类,比如我们这里指定 prefix = "demo" 这样,我们就能将以demo为前缀的配置项拿到了。
ps:其实这个注解很强大,它不但能映射成String或基本类型的变量。还可以映射为List,Map等数据结构。
@ConfigurationProperties(prefix = "spring.http.pool"
)
public class HttpClientProperties {private int maxTotal = 100;private int defaultMaxPerRoute = 20;private int connectTimeout = 3000;private int connectionRequestTimeout = 200;private int socketTimeout = 2000;private int validateAfterInactivity;private Long keepAliveTime = 20L;public HttpClientProperties() {}public int getMaxTotal() {return this.maxTotal;}public void setMaxTotal(int maxTotal) {this.maxTotal = maxTotal;}public int getDefaultMaxPerRoute() {return this.defaultMaxPerRoute;}public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {this.defaultMaxPerRoute = defaultMaxPerRoute;}public int getConnectTimeout() {return this.connectTimeout;}public void setConnectTimeout(int connectTimeout) {this.connectTimeout = connectTimeout;}public int getConnectionRequestTimeout() {return this.connectionRequestTimeout;}public void setConnectionRequestTimeout(int connectionRequestTimeout) {this.connectionRequestTimeout = connectionRequestTimeout;}public int getSocketTimeout() {return this.socketTimeout;}public void setSocketTimeout(int socketTimeout) {this.socketTimeout = socketTimeout;}public int getValidateAfterInactivity() {return this.validateAfterInactivity;}public void setValidateAfterInactivity(int validateAfterInactivity) {this.validateAfterInactivity = validateAfterInactivity;}public Map<String, Integer> getKeepAliveTargetHost() {return null;}public Long getKeepAliveTime() {return this.keepAliveTime;}public void setKeepAliveTime(Long keepAliveTime) {this.keepAliveTime = keepAliveTime;}
}

2.4 定义一个配置类

这里,我们将DemoService类定义为一个Bean,交给Ioc容器。

  • ▲  @Configuration 注解就不多说了。
  • ▲  @EnableConfigurationProperties 注解。该注解是用来开启对3步骤中 @ConfigurationProperties 注解配置Bean的支持。也就是@EnableConfigurationProperties注解告诉Spring Boot 能支持@ConfigurationProperties。

当然了,也可以在 @ConfigurationProperties 注解的类上添加 @Configuration 或者  @Component 注解

  • ▲  @ConditionalOnProperty 注解控制 @Configuration 是否生效。简单来说也就是我们可以通过在yml配置文件中控制 @Configuration 注解的配置类是否生效。
@Slf4j
@Configuration
@EnableConfigurationProperties({HttpClientProperties.class})
public class RestTemplateAutoConfiguration {@Autowiredprivate HttpClientProperties httpClientProperties;public RestTemplateAutoConfiguration() {}@Beanpublic RestTemplate restTemplate() {RestTemplate template = new RestTemplate(this.httpRequestFactory());template.getInterceptors().add(new LoggingReqRespInterceptor());return template;}@Beanpublic ClientHttpRequestFactory httpRequestFactory() {return new HttpComponentsClientHttpRequestFactory(this.httpClient());}@Beanpublic HttpClient httpClient() {Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build();PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);connectionManager.setMaxTotal(this.httpClientProperties.getMaxTotal());connectionManager.setDefaultMaxPerRoute(this.httpClientProperties.getDefaultMaxPerRoute());connectionManager.setValidateAfterInactivity(this.httpClientProperties.getValidateAfterInactivity());RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.httpClientProperties.getSocketTimeout()).setConnectTimeout(this.httpClientProperties.getConnectTimeout()).setConnectionRequestTimeout(this.httpClientProperties.getConnectionRequestTimeout()).build();HttpClientBuilder clientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager);try {SSLContext sslContext = (new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, (String[])null, NoopHostnameVerifier.INSTANCE);clientBuilder.setConnectionManager(connectionManager).setSSLSocketFactory(csf);clientBuilder.setKeepAliveStrategy(this.connectionKeepAliveStrategy2());} catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException var7) {log.error("SSL context configuring failed, HTTPS cannot be used in RestTemplate.", var7);}return clientBuilder.build();}/*** 金投的方法,e.getKey()出现报错* @return*//*public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {return (response, context) -> {BasicHeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Keep-Alive"));while(true) {String param;String value;do {do {if (!it.hasNext()) {HttpHost target = (HttpHost)context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);Optional<Map.Entry<String, Integer>> any = ((Map)Optional.ofNullable(this.httpClientProperties.getKeepAliveTargetHost()).orElseGet(HashMap::new)).entrySet().stream().filter((e) -> {return ((String)e.getKey()).equalsIgnoreCase(target.getHostName());}).findAny();return (Long)any.map((en) -> {return (long)(Integer)en.getValue() * 1000L;}).orElse(this.httpClientProperties.getKeepAliveTime() * 1000L);}HeaderElement he = it.nextElement();log.info("HeaderElement:{}", JSON.toJSONString(he));param = he.getName();value = he.getValue();} while(value == null);} while(!"timeout".equalsIgnoreCase(param));try {return Long.parseLong(value) * 1000L;} catch (NumberFormatException var8) {log.error("Error occurs while parsing timeout settings of keep-alived connection.", var8);}}};}*/public ConnectionKeepAliveStrategy connectionKeepAliveStrategy2(){return (response, context) -> {// Honor 'keep-alive' headerHeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));while (it.hasNext()) {HeaderElement he = it.nextElement();log.info("HeaderElement:{}", JSON.toJSONString(he));String param = he.getName();String value = he.getValue();if (value != null && "timeout".equalsIgnoreCase(param)) {try {return Long.parseLong(value) * 1000;} catch(NumberFormatException ignore) {log.error("解析长连接过期时间异常",ignore);}}}HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);//如果请求目标地址,单独配置了长连接保持时间,使用该配置Optional<Map.Entry<String, Integer>> any = Optional.ofNullable(httpClientProperties.getKeepAliveTargetHost()).orElseGet(HashMap::new).entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny();//否则使用默认长连接保持时间return any.map(en -> en.getValue() * 1000L).orElse(httpClientProperties.getKeepAliveTime() * 1000L);};}public static void main(String[] args) {System.out.println("###");}
}

2.5 spring.factories

如图,新建META-INF文件夹,然后创建spring.factories文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.qian.starter.web.RestTemplateAutoConfiguration

2.6 测试

1.在另一个项目中引入web-starter:

2.写一个测试类,注入restTemlate

3.运行testRest(),查看是否用了我们restTemplate

 如上图,证明restTemplate确实是我们web-starter里的实例,并且也执行了拦截器。

三、starter的基础——SPI

https://www.cnblogs.com/warrior4236/p/13280755.html

年轻人的第一个自定义Springboot starter相关推荐

  1. SpringSecurity Oauth2 - 自定义 SpringBoot Starter 远程访问受限资源

    文章目录 1. 自定义 SpringBoot Starter 1. 统一的dependency管理 2. 对外暴露 properties 3. 实现自动装配 4. 指定自动配置类的路径 META-IN ...

  2. twitter自定义api_为Twitter4j创建自定义SpringBoot Starter

    twitter自定义api SpringBoot提供了许多启动器模块来快速启动和运行. SpringBoot的自动配置机制负责根据各种标准代表我们配置SpringBean. 除了Core Spring ...

  3. 自定义SpringBoot Starter实现

    文章目录 自定义stater pom文件 配置文件类properties 使用配置类 创建AutoConfiguration 项目结构 自定义stater pom文件 引入自动配置类spring-bo ...

  4. 为Twitter4j创建自定义SpringBoot Starter

    SpringBoot提供了许多启动器模块来快速启动和运行. SpringBoot的自动配置机制负责根据各种标准代表我们配置SpringBean. 除了Core Spring Team提供的现成的spr ...

  5. 简述SpringBoot Starter原理及自定义实现

    简述SpringBoot Starter原理及自定义实现 一.简述 二.结合SpringBoot启动原理看容器如何实现自动装配 三.解析mybatis-spring-boot-starter包看myb ...

  6. 自定义一个SpringBoot Starter

    文章目录 简介 使用Spring Initializr创建一个项目 定义一个配置信息映射类 定义一个Service 定义一个配置类自动装配Service 在spring.factories中指定自动装 ...

  7. 深入理解springboot starter

    定义:Spring Boot Starter 是在 SpringBoot 组件中被提出来的一种概念,官网概念 Starter POMs are a set of convenient dependen ...

  8. 第一节:创建SpringBoot项目并运行HelloWorld

    SpingBoot 365计划开始更新了,计划手敲365个SpringBoot案例回顾总结形成知识体系.目前已经输出了32节的内容.所有源码托管在GitHub和Gitee上. 1.第一节:创建Spri ...

  9. 【微信开发第一章】SpringBoot实现微信公众号创建菜单,同步菜单功能

    前言 在进行微信公众号业务开发的时候,微信公众号的自定义菜单是非常重要的一环,该篇文章会先使用微信测试工具过一遍流程,再使用代码进行实现,争取看过的小伙伴都能够实现,创建公众号菜单和代码同步公众号菜单 ...

  10. 实现第一个自定义nginx模块

    实现第一个自定义nginx模块 下面的过程详细记录了如何实现第一个自定义的nginx模块,对nginx入门者包括我很有参考价值,特记录如下. 前提 假定以root身份已经在CentOS 6.8 x86 ...

最新文章

  1. Java锁机制学习笔记——synchronized 和 Lock
  2. JavaScript判断图片是否加载完成的三种方式
  3. ajax传向前台的html代码里又有事件的时候,绑定事件失败解决方法
  4. IDEA 部署项目的时候出错:Jar not loaded错误
  5. 《Flowable基础二 Flowable是什么》
  6. wordpress 当前栏目名,当前栏目的分类名
  7. 正则表达式如何匹配正反斜杠
  8. svgaps绘制时不能用中文命名吗_设计师需要了解的切图命名规范
  9. 数据增长浪潮下,PCIe 6.0的问与Rambus的答
  10. vs2008添加注释宏(暂未成功设置)
  11. 我们都在努力做自己,我的编程之路开篇
  12. 人脸识别中常用的几种分类器
  13. SynthMaster One波表合成器绿色版亲测有效
  14. 珍藏版《一步一步学PLC编程》全套资料!
  15. 汽车品牌查询及车型大全查询
  16. UML--构件图详解
  17. android 判断是夜神模拟器,查看夜神模拟器版本的三种技巧
  18. Linux重置root密码和Linux基础命令
  19. 【LeetCode力扣】青蛙跳台阶问题,一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
  20. python抠图教程视频_Python快速抠图不比PS差!1分钟搞定!

热门文章

  1. java技术架构选型方案报告.pdf,来啦,2020开源报告!
  2. tensorflow 2.5.0 ( keras )搭建wgan-gp 和 div
  3. 用html语言写一个环形,html5环形流程图可添加流程图代码
  4. Google Code Review代码审查标准
  5. 153.寻找旋转排序数组中的最小值
  6. 谈谈Cost function and gradient的matlab写法
  7. Prometheus自动发现Exporter实现方案(一看就懂)
  8. 目标追踪论文之狼吞虎咽(2):在线被动攻击学习
  9. 不动点迭代法的收敛阶
  10. ConcurrentHashMap源码分析(保姆式讲解):Put、扩容原理详解 博主可答疑