引言

只要你用Springboot,一定会用到各种spring-boot-starter。其实写一个spring-boot-starter,仅需4步。下面我们就写一个starter,它将实现,在日志中打印方法执行时间。

推荐一个艿艿写的 6000+ Star 的 SpringBoot + SpringCloud + Dubbo 教程的仓库:https://github.com/YunaiV/SpringBoot-Labs

第一步 创建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中。

推荐一个艿艿写的 3000+ Star 的 SpringCloud Alibaba 电商开源项目的仓库:https://github.com/YunaiV/onemall

第二步写自动配置逻辑

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

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

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

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

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

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者 | 温安适 来源 | https://my.oschina. ...

  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. 机器学习研究人员需要学习8种神经网络架构
  2. 今后军队将完全人工智能化?停止幻想!大趋势和大方向不容改变
  3. divcss布局模板代码_(带手机版数据同步)房产门户企业织梦模板 房地产楼盘网站源码下载...
  4. VC下调用x264进行视频编码,
  5. 【技术+某度面经】Jenkins 内容+百度面经分享
  6. iOS应用性能调优建议
  7. 【Flutter】Dart的方法与箭头函数
  8. AS技巧合集「编码技巧篇」
  9. carto笔记--- 传感器数据走向
  10. 20151221jquery学习笔记--验证插件
  11. zabbix server is not running解决办法
  12. 153.寻找旋转排序数组中的最小值(力扣leetcode) 博主可答疑该问题
  13. Codevs 2800 送外卖(状压DP)
  14. 数据库性能优化的五种方案
  15. 服务器 支持sata硬盘,服务器SAS硬盘背板能插SATA硬盘吗?
  16. WARNING: The scripts f2py, f2py3 and f2py3.6 are installed in ‘/home/nano/.local/bin‘ which is not o
  17. 找出数组中出现次数最多的数字和出现次数
  18. [MIT]微积分重点 第十七课 六函数、六法则和六定理 学习笔记
  19. 痛心!中兴程序员跳楼始末:或成其公司内部矛盾牺牲品
  20. Mac清理磁盘管理内存的软件推荐

热门文章

  1. 深度学习(六)caffe入门学习
  2. 获取指定目录下的所有文件名
  3. 信息项目管理师-整体管理知识点
  4. 探索PHP7(一)--性能
  5. MYSQL如何导出存储过程和触发器?
  6. Excel插件类库的设计思路
  7. 悟透JavaScript (强烈推荐)
  8. HTML引入JS、CSS的各种方法
  9. DPM(Deformable Part Model)原理详解
  10. IDEA——使用JSONObject时报错