点击上方“方志朋”,选择“设为星标”

回复”666“获取新整理的面试文章

作者 | 温安适

来源 | https://my.oschina.net/floor/blog/4435699

引言

只要你用Springboot,一定会用到各种spring-boot-starter。其实写一个spring-boot-starter

,仅需4步。下面我们就写一个starter,它将实现,在日志中打印方法执行时间。

第一步 创建maven项目

在使用spring-boot-starter,会发现,有的项目名称是 XX-spring-boot-starter,有的是

spring-boot-starter-XX,这个项目的名称有什么讲究呢?

从springboot官方文档摘录如下:

Do not start your module names with spring-boot, even if you use a different Maven groupId. We may offer official support for the thing you auto-configure in the future.

As a rule of thumb, you should name a combined module after the starter.

从这段话可以看出spring-boot-starter命名的潜规则。

命名潜规则

spring-boot-starter-XX是springboot官方的starter

XX-spring-boot-starter是第三方扩展的starter

打印方法执行时间的功能,需要用到aop,咱们的项目就叫做

aspectlog-spring-boot-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"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>aspectlog-spring-boot-starter</artifactId><version>1.0.2</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.15.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies></project>

关于spring-boot-configuration-processor的说明,引自springBoot官方文档:

Spring Boot uses an annotation processor to collect the conditions on auto-configurations in a metadata file ( META-INF/spring-autoconfigure-metadata.properties ). If that file is present, it is used to eagerly filter auto-configurations that do not match, which will improve startup time. It is recommended to add the following dependency in a module that contains auto-configurations:

org.springframework.boot

spring-boot-autoconfigure-processor

true

简单说就是:写starter时,在pom中配置spring-boot-autoconfigure-processor,在编译时会自动收集配置类的条件,写到一个META-INF/spring-autoconfigure-metadata.properties中。

第二步写自动配置逻辑

各种condition

类型 注解 说明
Class Conditions类条件注解 @ConditionalOnClass 当前classpath下有指定类才加载
@ConditionalOnMissingClass 当前classpath下无指定类才加载
Bean ConditionsBean条件注解 @ConditionalOnBean 当期容器内有指定bean才加载
@ConditionalOnMissingBean 当期容器内无指定bean才加载
Property Conditions环境变量条件注解(含配置文件) @ConditionalOnProperty prefix 前缀name 名称havingValue 用于匹配配置项值matchIfMissing 没找指定配置项时的默认值
ResourceConditions 资源条件注解 @ConditionalOnResource 有指定资源才加载
Web Application Conditionsweb条件注解 @ConditionalOnWebApplication 是web才加载
@ConditionalOnNotWebApplication 不是web才加载
SpEL Expression Conditions @ConditionalOnExpression 符合SpEL 表达式才加载

本次我们就选用@ConditionalOnProperty。即配置文件中有aspectLog.enable=true,才加载我们的配置类。

下面开始写自动配置类

2.1.定义AspectLog注解,该注解用于标注需要打印执行时间的方法。

package com.shanyuan.autoconfiguration.aspectlog;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*** class_name: ScheduleManage* describe:   用于控制定时任务的开启与关闭* 对应切面* creat_user: wenl* creat_time:  2018/11/10 18:45**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface   AspectLog {
}

2.2定义配置文件对应类

package com.shanyuan.autoconfiguration.aspectlog;
import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties("aspectLog")
public class AspectLogProperties {private boolean enable;public boolean isEnable() {return enable;}public void setEnable(boolean enable) {this.enable = enable;}
}

2.3定义自动配置类

package com.shanyuan.autoconfiguration.aspectlog;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.PriorityOrdered;@Aspect
@EnableAspectJAutoProxy(exposeProxy = true, proxyTargetClass = true)
@Configuration
@ConditionalOnProperty(prefix = "aspectLog", name = "enable",havingValue = "true", matchIfMissing = true)
public class AspectLogAutoConfiguration implements PriorityOrdered {protected Logger logger = LoggerFactory.getLogger(getClass());@Around("@annotation(com.shanyuan.autoconfiguration.aspectlog.AspectLog) ")public Object isOpen(ProceedingJoinPoint thisJoinPoint) throws Throwable {//执行方法名称 String taskName = thisJoinPoint.getSignature().toString().substring(thisJoinPoint.getSignature().toString().indexOf(" "), thisJoinPoint.getSignature().toString().indexOf("("));taskName = taskName.trim();long time = System.currentTimeMillis();Object result = thisJoinPoint.proceed();logger.info("method:{} run :{} ms", taskName, (System.currentTimeMillis() - time));return result;}@Overridepublic int getOrder() {//保证事务等切面先执行return Integer.MAX_VALUE;}
}

配置类简要说明:

@ConditionalOnProperty(prefix = "aspectLog", name = "enable",havingValue = "true", matchIfMissing = true)

当配置文件有aspectLog.enable=true时开启,如果配置文件没有设置aspectLog.enable也开启。

第三步META-INF/spring.factories

META-INF/spring.factories是spring的工厂机制,在这个文件中定义的类,都会被自动加载。多个配置使用逗号分割,换行用\

如果有兴趣可以查看这2篇blog:

2.@Enable驱动原理(设置连接)

3.@EnableAutoConfiguration处理逻辑(设置连接)

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.shanyuan.autoconfiguration.aspectlog.AspectLogAutoConfiguration

第四步打包测试

这是我们最终的目录结构

在IDEA中,进行mvn intall

打包完成后,在其他项目中的pom中引入进行测试

参考资料

  • https://docs.spring.io/spring-boot/docs/2.1.15.RELEASE/reference/html/boot-features-developing-auto-configuration.html#boot-features-custom-starter

热门内容:记一次订单号重复的事故,快看看你的 uuid 在并发下还正确吗?JAVA 线上故障排查完整套路,从 CPU、磁盘、内存、网络、GC 一条龙!
IDEA中一个被低估的功能,一键把项目代码绘制成UML类图
最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。
明天见(。・ω・。)ノ

只需4步,自己搞个 Spring Boot Starter !相关推荐

  1. 手机如何去视频水印?只需几步轻松搞定

    手机如何去视频水印?只需几步轻松搞定 很多人对于ps相关的功能有极大的误解,认为必须通过专业的软件才能够实现,而且很多专业的ps软件并不是仅仅拥有一部手机就能够使用的,还需要具备一定配置的电脑. 其实 ...

  2. 只需 4 步,自己搞个 Spring Boot Starter!

    引言 只要你用Springboot,一定会用到各种spring-boot-starter.其实写一个spring-boot-starter,仅需4步.下面我们就写一个starter,它将实现,在日志中 ...

  3. 抽奖随机滚动_手把手教你制作EXCEL抽奖器,只需两步轻松搞定

    [例一]利用CHOOSE函数和RANDBETWEEN函数进行抽奖设置.如下图: 目的:在B列随机生成1-50的随机整数,取号码末尾数值,对应奖品,当末尾数值大于5时,为空奖. 操作: 第一步:在B2单 ...

  4. 电脑计算机音乐删了怎么找回,电脑中误删除的音乐文件如何恢复?只需五步即可搞定!...

    当我们宅在家里做家务时,或者是坐车无聊时,我们都会打开手机上的音乐软件,播放音乐听听歌曲,来让劳动或无聊的时间变得更加轻松.快乐. 而有的人喜欢用手机听歌,而有的人喜欢用电脑听歌,如果使用电脑听歌的话 ...

  5. java request 克隆_Java 复制HttpServletRequest InputStream的方法 只需2步轻松搞定

    你可能很疑惑,为什么request对象中的InputStream或者Reader只能使用一次? 原理很简单,可以把流比喻成水,request里面的inputStream就好比杯子中的水.试问杯子中的水 ...

  6. 在线qmc0转换mp3工具_如何将M4A格式的音频转换为MP3格式?只需一步搞定

    随着网络技术的发达,会有很多人喜欢在网上下载东西,特别是很喜欢在网上下载音乐,但是下载音乐之后发现是M4A格式?这样用起来很不方便,都喜欢MP3格式的,那么如何将M4A格式的音频转换为MP3格式?今天 ...

  7. 如何将M4A格式的音频转换为MP3格式?只需一步搞定

    随着网络技术的发达,会有很多人喜欢在网上下载东西,特别是很喜欢在网上下载音乐,但是下载音乐之后发现是M4A格式?这样用起来很不方便,都喜欢MP3格式的,那么如何将M4A格式的音频转换为MP3格式?今天 ...

  8. 计算机内存4g如何,电脑内存4G升到8G,只需三步,让你轻松搞定笔记本内存升级...

    今日看点:电脑内存4G升到8G,只需三步,让你轻松搞定笔记本内存升级 大家好,这期小编给大家讲讲怎么给笔记本升级电脑内存,小编现在用的是朋友的笔记本,小编发现朋友的笔记本的内存只有4GB.小编每次用p ...

  9. 计算机一级b证书图片p,只需两步,分分钟搞定证件照(内附福利)

    原标题:只需两步,分分钟搞定证件照(内附福利) 简历中要不要放证件照? 当然要! 怎么样才能让证件照成为求职过程中的加分项? 不浮夸,不造作! 证件照怎么拍? 不要998,小V教你在家就能自制最美证件 ...

最新文章

  1. 清华团队将Transformer用到3D点云分割上后,效果好极了
  2. 用CSS在博客园底部加上蒲公英动态效果的实现方法
  3. 【项目管理】各种常用工具图表说明和示例
  4. 白话详细解读(一)-----GoogLeNet(Inception V1-Inception V3)
  5. nextgaussian_Java Random nextGaussian()方法与示例
  6. 如何打印出给定尺寸的方格_打印给定号码的表格| 8085微处理器
  7. 《Ansible权威指南 》一第2章 Ansible基础元素介绍
  8. MyEclipse断点调试不可用解决办法
  9. Arrays类及其方法分析
  10. 《那些年啊,那些事——一个程序员的奋斗史》——65
  11. 在浏览器中进行深度学习:TensorFlow.js (二)第一个模型,线性回归
  12. java读加密脚本_尝试将wlst脚本嵌入到java类中时发生加密错误
  13. python3 open打开文件_Python3基础 file open 打开txt文件并打印出全文
  14. 小胖月安卓版,随机选号、叫号功能,互动功能
  15. git提交代码时遇到代码库有更新以及本地有更新的解决方法
  16. 乐谱xml文件转为VOCALOID3的输入文件格式vsqx
  17. Modern UI for WPF的使用
  18. 球的表面积公式是怎么推导出来的?
  19. 华为海思芯片型号及特征大全
  20. IT经济合同的工程量清单计价技巧

热门文章

  1. 利用Python制作简单的小程序:IP查看器
  2. 关于查询ios的app更新的历史版本记录
  3. WPF XAML 资源样式模板属性存放位置
  4. 连接Oracle错误:800a0e7a未找到提供程序的解决
  5. openstack安装在虚拟机上重启之后无法启动问题
  6. Yii在window下的安装方法
  7. 算法基础知识科普:8大搜索算法之二叉搜索树(下)
  8. 【牛客】简单排序 (STL)
  9. 【ACM】杭电OJ 1862
  10. 凝聚406万开发者 飞桨十大发布提速产业智能化