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

沙海 2021年6月16日12:12:56Java评论22字数 6728阅读22分25秒阅读模式
摘要

只需4步,自己搞个 Spring Boot Starter ! 搜云库技术团队

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

搜云库技术团队 文章源自JAVA秀-https://www.javaxiu.com/32647.html

大家好,我是磊哥。文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

引言文章源自JAVA秀-https://www.javaxiu.com/32647.html

只要你用Springboot,一定会用到各种spring-boot-starter。其实写一个spring-boot-starter,仅需4步。下面我们就写一个starter,它将实现,在日志中打印方法执行时间。文章源自JAVA秀-https://www.javaxiu.com/32647.html

第一步 创建maven项目

在使用spring-boot-starter,会发现,有的项目名称是 XX-spring-boot-starter,有的是文章源自JAVA秀-https://www.javaxiu.com/32647.html

spring-boot-starter-XX,这个项目的名称有什么讲究呢?文章源自JAVA秀-https://www.javaxiu.com/32647.html

注 意文章源自JAVA秀-https://www.javaxiu.com/32647.html

 文末有:3625页互联网大厂面试题 文章源自JAVA秀-https://www.javaxiu.com/32647.html

从springboot官方文档摘录如下:文章源自JAVA秀-https://www.javaxiu.com/32647.html

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.文章源自JAVA秀-https://www.javaxiu.com/32647.html

从这段话可以看出spring-boot-starter命名的潜规则。文章源自JAVA秀-https://www.javaxiu.com/32647.html

命名潜规则

spring-boot-starter-XX是springboot官方的starter文章源自JAVA秀-https://www.javaxiu.com/32647.html

XX-spring-boot-starter是第三方扩展的starter文章源自JAVA秀-https://www.javaxiu.com/32647.html

打印方法执行时间的功能,需要用到aop,咱们的项目就叫做文章源自JAVA秀-https://www.javaxiu.com/32647.html

aspectlog-spring-boot-starter吧。文章源自JAVA秀-https://www.javaxiu.com/32647.html

项目的pom文件如下:文章源自JAVA秀-https://www.javaxiu.com/32647.html

<?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官方文档:文章源自JAVA秀-https://www.javaxiu.com/32647.html

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:文章源自JAVA秀-https://www.javaxiu.com/32647.html

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-autoconfigure-processor</artifactId>    <optional>true</optional></dependency>

简单说就是 写starter时,在pom中配置spring-boot-autoconfigure-processor, 在编译时会自动收集配置类的条件,写到一个META-INF/spring-autoconfigure-metadata.properties中文章源自JAVA秀-https://www.javaxiu.com/32647.html

第二步写自动配置逻辑

各种condition文章源自JAVA秀-https://www.javaxiu.com/32647.html

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

本次我们就选用@ConditionalOnProperty。即配置文件中有aspectLog.enable=true,才加载我们的配置类。下面开始写自动配置类文章源自JAVA秀-https://www.javaxiu.com/32647.html

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;    }    @Override    public int getOrder() {        //保证事务等切面先执行        return Integer.MAX_VALUE;    }}

配置类简要说明:文章源自JAVA秀-https://www.javaxiu.com/32647.html

@ConditionalOnProperty(prefix = "aspectLog", name = "enable",havingValue = "true", matchIfMissing = true)文章源自JAVA秀-https://www.javaxiu.com/32647.html

当配置文件有aspectLog.enable=true时开启,如果配置文件没有设置aspectLog.enable也开启。文章源自JAVA秀-https://www.javaxiu.com/32647.html

第三步META-INF/spring.factories

META-INF/spring.factories是spring的工厂机制,在这个文件中定义的类,都会被自动加载。多个配置使用逗号分割,换行用\文章源自JAVA秀-https://www.javaxiu.com/32647.html

如果有兴趣可以查看这2篇blog:文章源自JAVA秀-https://www.javaxiu.com/32647.html

2、@Enable驱动原理(设置连接)文章源自JAVA秀-https://www.javaxiu.com/32647.html

3、@EnableAutoConfiguration处理逻辑(设置连接)文章源自JAVA秀-https://www.javaxiu.com/32647.html

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

第四步打包测试

这是我们最终的目录结构文章源自JAVA秀-https://www.javaxiu.com/32647.html

只需4步,自己搞个 Spring Boot Starter !文章源自JAVA秀-https://www.javaxiu.com/32647.html

97_1.png文章源自JAVA秀-https://www.javaxiu.com/32647.html

在IDEA中,进行mvn intall文章源自JAVA秀-https://www.javaxiu.com/32647.html

只需4步,自己搞个 Spring Boot Starter !文章源自JAVA秀-https://www.javaxiu.com/32647.html

97_2.png文章源自JAVA秀-https://www.javaxiu.com/32647.html

打包完成后,在其他项目中的pom中引入进行测试文章源自JAVA秀-https://www.javaxiu.com/32647.html

只需4步,自己搞个 Spring Boot Starter !文章源自JAVA秀-https://www.javaxiu.com/32647.html

作者 | 温安适文章源自JAVA秀-https://www.javaxiu.com/32647.html

来源 | my.oschina.net/floor/blog/4435699文章源自JAVA秀-https://www.javaxiu.com/32647.html

参考资料文章源自JAVA秀-https://www.javaxiu.com/32647.html

https://docs.spring.io/spring-boot/docs/2.1.15.RELEASE/reference/html/boot-features-developing-auto-configuration.html#boot-features-custom-starter文章源自JAVA秀-https://www.javaxiu.com/32647.html

近期技术热文文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

Google 开源的依赖注入库,比 Spring 更小更快!文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

Intellij IDEA 居然,还有这些,提效小技巧!文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

为什么大家都说SELECT * 效率低文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

MyBatis 的执行流程,写得也太全了吧!文章源自JAVA秀-https://www.javaxiu.com/32647.html

文章源自JAVA秀-https://www.javaxiu.com/32647.html

第3版:互联网大厂面试题文章源自JAVA秀-https://www.javaxiu.com/32647.html

包括 Java 集合、JVM、多线程、并发编程、设计模式、算法调优、Spring全家桶、Java、MyBatis、ZooKeeper、Dubbo、Elasticsearch、Memcached、MongoDB、Redis、MySQL、RabbitMQ、Kafka、Linux、Netty、Tomcat、Python、HTML、CSS、Vue、React、JavaScript、Android 大数据、阿里巴巴等大厂面试题等、等技术栈!文章源自JAVA秀-https://www.javaxiu.com/32647.html

阅读原文: 高清 7701页大厂面试题  PDF文章源自JAVA秀-https://www.javaxiu.com/32647.html

继续阅读
速蛙云 - 极致体验,强烈推荐!!!购买套餐就免费送各大视频网站会员!快速稳定、独家福利社、流媒体稳定解锁!速度快,全球上网、视频、游戏加速、独立IP均支持!基础套餐性价比很高!这里不多说,我一直正在使用,推荐购买:https://www.javaxiu.com/59919.html
weinxin
资源分享QQ群
本站是JAVA秀团队的技术分享社区, 会经常分享资源和教程; 分享的时代, 请别再沉默!
沙海
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定