天天看點

僅需四步,寫一個springboot starter引言第一步 建立maven項目第二步寫自動配置邏輯第三步META-INF/spring.factories第四步打包測試

這個系列分為5篇

1. @Component,@Service等注解是如何被解析的

2. @Enable驅動原理

3. @EnableAutoConfiguration處理邏輯

4. spring,springBoot事件

5.僅需四步,寫一個springboot starter

引言

隻要你用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:

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

第二步寫自動配置邏輯

各種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;
    }
    @Override
    public 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           

複制

第四步打包測試

這是我們最終的目錄結構

僅需四步,寫一個springboot starter引言第一步 建立maven項目第二步寫自動配置邏輯第三步META-INF/spring.factories第四步打包測試

在IDEA中,進行mvn intall

僅需四步,寫一個springboot starter引言第一步 建立maven項目第二步寫自動配置邏輯第三步META-INF/spring.factories第四步打包測試

打包完成後,在其他項目中的pom中引入進行測試

僅需四步,寫一個springboot starter引言第一步 建立maven項目第二步寫自動配置邏輯第三步META-INF/spring.factories第四步打包測試

參考資料

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