ホットスワップ可能なコンポーネントのカスタマイズ - Spring-boot-starter 実装で

1. 事前知識ポイント

このチュートリアルを学習するには、特定の事前知識が必要です

1> Maven の使用に習熟している

2> Web システムに精通している

3> Spring/SpringMVC フレームワークの上手な使い方

4> SpringBoot フレームワークの使用に習熟している

5> Java ログに精通している (デモンストレーション ケース)

2. スターターを出す

Spring-boot-starter のシンプルさを感じる例を見てみましょう

要件: Web プロジェクトをビルドし、次のサイトにアクセスします: http://localhost:8080/hello Return: Hello, Langfei yes

2.1 従来の Spring MVC

ステップ 1: project-mvc-demo を作成する

ステップ 2: 依存パッケージをインポートする

<properties>
	<spring.version>5.0.8.RELEASE</spring.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>3.0.1</version>
		<scope>provided</scope>
	</dependency>
</dependencies>
<build>
	<plugins>
		<plugin>
			<groupId>org.apache.tomcat.maven</groupId>
			<artifactId>tomcat7-maven-plugin</artifactId>
			<version>2.1</version>
			<configuration>
				<port>8080</port>
				<path>/</path>
				<uriEncoding>UTF-8</uriEncoding>
			</configuration>
		</plugin>
	</plugins>
</build>

ステップ 3: Web 構成

resources ディレクトリに新しい mvc.xml を作成し、次のように構成します。

<!-- 配置 IoC DI 注解解析器,让 Spring 我们创建 HelloController 类的对象 -->
<context:component-scan base-package="com.langfeiyes.mvc.controller"/>
<!-- MVC 注解解析器 -->
<mvc:annotation-driven/>

メイン ディレクトリに新しい webapp/WEB-INF/web.xml を作成します。内容は次のとおりです。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <!-- Spring MVC 前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 指定 Spring 容器启动加载的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <!-- Tomcat 启动初始化 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

ステップ 4: コードを書く

package com.langfeiyes.mvc.controller;

@RestController
public class HelloController {
    // 提供方法处理请求,在浏览器地址栏输入如下 localhost/hello,就会执行下面的方法
    @RequestMapping("/hello") 
    public String save() {
        return "hello, 浪飞yes";
    }
}

ステップ 5: テスト

ブラウザーを開き、アドレス バーにhttp://localhost:8080/helloと入力し、 にアクセスして効果を確認します。

2.2 SpringBoot のスターターのオーバーレイ

ステップ 1: project-starter-demo を作成する

ステップ 2: 依存パッケージをインポートする


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.3.RELEASE</version>
</parent>

<dependencies>    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

ステップ 3: コードを書く

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello,浪飞yes";
    }
}

ステップ 4: テスト

スタートアップ クラスのスタートアップ プロジェクトを作成する

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

ブラウザーを開き、アドレス バーにhttp://localhost:8080/helloと入力し、 にアクセスして効果を確認します。

ここでまず、Starter の最も注目すべき機能を思い出してください:開発を容易にする

3.スターターとは

上記の 2 つの Web プロジェクトの比較から、SpringBoot を重ねた SpringMVC 操作は、従来の Spring MVC とは異なり、xml 構成ファイルの束とは異なり、xml 構成を無視すると、プロジェクト全体が使いやすくなることがわかります。複雑な xml ファイルがたくさんあると、それらを解決する方法がわかりません. この人生で愛するものが何もないのは不快です.

しかし、SpringBoot + Starter を持っているので、世界が良くなることはありません。

では、SpringBoot とは何ですか? Starter とは何ですか?

3.1 スプリング ブートのレビュー

SpringBoot はいくつかの点を簡単に要約しています。

1> Jar コレクター、さまざまな一般的なサードパーティ フレームワーク/コンポーネントの jar を収集

2>ガジェット愛好家は、収集したjarをモジュール/機能に従って分類および要約し、より大きな機能jarパッケージを取得します:スターター

3>小さな専門家を自動的に構成し、jarの導入に応じて、さまざまな機能をプロジェクトに自動的にロードします

SpringBoot の詳細な操作についてはここでは説明しません. 事前知識のポイントに属します. 基礎のない友人は、私の B ステーション スペースに行って、SpringBoot の紹介ビデオを見ることができます. <<SpringBoot入社から企業実戦まで、新人からベテランまで6時間~>>

またはcsdnコース

入門から習熟まで 8 時間 - SpringBoot

3.2 Spring Boot スターター

Spring-boot-starter は SpringBoot スターターと呼ばれ、Spring Boot は、アプリケーションが必要とする基本的な依存関係 (jar) に基づいて依存関係ライブラリ (jar) のコレクションをカスタマイズし、Spring アプリケーションをすばやく起動するために使用できます。例: spring-boot-starter-web をインポートすると mvc 環境全体を導入でき、インポート: spring-boot-starter-Redis は Redis データベースを直接使用できます。

Spring-boot-starter は、分離可能で再利用可能なホットスワップ可能なモジュールとして設計されているため、Spring プログラムの構築プロセスが大幅に簡素化され、プログラム設計の柔軟性が向上します。

3.3 一般的な Spring-Boot-Starter

スターターは2種類あり、

  • SpringBoot のデフォルト、Spring 公式によってカスタマイズされたもの

命名形式:spring-boot-starter-{モジュール名}

コモンスターター

spring-boot-starter 这是Spring Boot的核心启动器,包含了自动配置、日志和YAML。
spring-boot-starter-actuator 帮助监控和管理应用。
spring-boot-starter-amqp 通过spring-rabbit来支持AMQP协议
spring-boot-starter-aop 支持面向方面的编程即AOP,包括spring-aop和AspectJ。
spring-boot-starter-artemis 通过Apache Artemis支持JMS的API(Java Message Service API)。
spring-boot-starter-batch 支持Spring Batch,包括HSQLDB数据库。
spring-boot-starter-cache 支持Spring的Cache抽象。
spring-boot-starter-cloud-connectors 支持Spring Cloud Connectors,简化了在像Cloud Foundry或Heroku这样的云平台上连接服务。
spring-boot-starter-data-elasticsearch 支持ElasticSearch搜索和分析引擎,包括spring-data-elasticsearch。
spring-boot-starter-data-gemfire 支持GemFire分布式数据存储,包括spring-data-gemfire。
spring-boot-starter-data-jpa 支持JPA(Java Persistence API),包括spring-data-jpa、spring-orm、hibernate。
spring-boot-starter-data-MongoDB 支持MongoDB数据,包括spring-data-mongodb。
spring-boot-starter-data-rest 通过spring-data-rest-webmvc,支持通过REST暴露Spring Data数据仓库。
spring-boot-starter-data-solr 支持Apache Solr搜索平台,包括spring-data-solr。
spring-boot-starter-freemarker 支持FreeMarker模板引擎。
spring-boot-starter-groovy-templates 支持Groovy模板引擎。
spring-boot-starter-hateoas 通过spring-hateoas支持基于HATEOAS的RESTful Web服务。
spring-boot-starter-hornetq 通过HornetQ支持JMS。
spring-boot-starter-integration 支持通用的spring-integration模块。
spring-boot-starter-jdbc 支持JDBC数据库。
spring-boot-starter-jersey 支持Jersey RESTful Web服务框架。
spring-boot-starter-jta-atomikos 通过Atomikos支持JTA分布式事务处理。
spring-boot-starter-jta-bitronix 通过Bitronix支持JTA分布式事务处理。
spring-boot-starter-mail 支持javax.mail模块。
spring-boot-starter-mobile 支持spring-mobile。
spring-boot-starter-mustache 支持Mustache模板引擎。
spring-boot-starter-Redis 支持Redis键值存储数据库,包括spring-redis。
spring-boot-starter-security 支持spring-security。
spring-boot-starter-social-facebook 支持spring-social-facebook
spring-boot-starter-social-linkedin 支持pring-social-linkedin
spring-boot-starter-social-twitter 支持pring-social-twitter
spring-boot-starter-test 支持常规的测试依赖,包括JUnit、Hamcrest、Mockito以及spring-test模块。
spring-boot-starter-thymeleaf 支持Thymeleaf模板引擎,包括与Spring的集成。
spring-boot-starter-velocity 支持Velocity模板引擎。
spring-boot-starter-web S支持全栈式Web开发,包括Tomcat和spring-webmvc。
spring-boot-starter-websocket 支持WebSocket开发。
spring-boot-starter-ws 支持Spring Web Services。
spring-boot-starter-remote-shell 增加了远程ssh shell的支持。
spring-boot-starter-jetty 引入了Jetty HTTP引擎(用于替换Tomcat)。
spring-boot-starter-log4j 支持Log4J日志框架。
spring-boot-starter-logging 引入了Spring Boot默认的日志框架Logback。
spring-boot-starter-tomcat 引入了Spring Boot默认的HTTP引擎Tomcat。
spring-boot-starter-undertow 引入了Undertow HTTP引擎(用于替换Tomcat)
  • サードパーティのカスタマイズ

SpringBoot によって開発されたスターターのカスタマイズ規則に従って、多くのサードパーティ組織が SpringBoot を組み合わせて独自のスターターをカスタマイズしています。

命名形式: {モジュール名}-spring-boot-starter

mybatis-spring-boot-starter:该starter提供了MyBatis框架的集成支持,可以帮助开发人员更快地搭建基于MyBatis的应用程序。

dubbospring-boot-starter:该starter提供了Dubbo分布式服务框架的集成支持,可以帮助开发人员更快地实现微服务架构。

elasticsearch-spring-boot-starter:该starter提供了Elasticsearch搜索引擎的集成支持,可以帮助开发人员更快地搭建基于Elasticsearch的搜索服务。

logstash-spring-boot-starter:该starter提供了Logstash日志收集框架的集成支持,可以帮助开发人员更快地集成Logstash服务。

druid-spring-boot-starter:该starter提供了Druid数据库连接池的集成支持,可以帮助开发人员更快地实现数据库连接池功能。

4.スターターのカスタマイズ方法

Starter のカスタマイズ方法に答える前に、まず 1 つのことを理解する必要があります: なぜカスタマイズするのか?

4.1 カスタマイズする理由

日常の開発作業では、業務に依存しない機能モジュールが存在することが多く、従来のアプローチでは、プロジェクト内に直接コーディングします。この機能モジュールを別のプロジェクトで再利用する場合、コードをハードコピーしてから再度統合する必要があり、この作業を繰り返すのは非常に面倒です。ビジネスから独立できるこれらの機能モジュールがスターターにパッケージ化され、再利用時に pom で依存関係を参照するだけでよいとしたら、クールだと思いませんか?

例えば、以下の業務外機能モジュール

1>一般モジュール - SMS送信モジュール

2> AOP テクノロジー ログの側面に基づく

3> 分散型スノーフレーク Long 型 ID の精度低下問題

4> マイクロサービス プロジェクトのデータベース接続プールの構成

5>マイクロサービスプロジェクト向けRedisデータベースの導入

6> マルチモジュール プロジェクト認証コンポーネントによって引き起こされる問題

4.2 スターターのカスタム実装

前者の場合、設計はより単純で、印刷操作は単純に傍受されます。

4.2.1 要件の説明

要件: インターセプト スターターを設計し、プロジェクト内のすべてのリクエストをインターセプトし、構成された情報情報を出力します。

要件:

yml で mvc.interceptor.show の値を構成して、有効にするか無効にするかを決定します

mvc:
  interceptor:
    info: hello,浪飞yes
    show: true

 

4.2.2 実装手順

1> プロジェクトを作成します。intercept-show-spring-boot-starter

2> 関連する依存関係をインポートする

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.2.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <scope>compile</scope>
    </dependency>

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

3>受信リソース構成ShowProperties構成クラスを定義します

2 つのリソース構成があります: info/show

mvc:
  interceptor:
    info: hello,浪飞yes...
    show: true

受入クラス

package com.langfeiyes.mvc.prop;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "mvc.interceptor")
public class ShowProperties {
    private boolean show = true;

    private String info;

    public boolean isShow() {
        return show;
    }

    public void setShow(boolean show) {
        this.show = show;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

4>インターセプターの定義-ShowInfoInterceptor

package com.langfeiyes.mvc.interceptor;

import com.langfeiyes.mvc.prop.ShowProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShowInfoInterceptor implements HandlerInterceptor {

    @Autowired
    private ShowProperties showProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (showProperties.isShow()){
            if (StringUtils.hasText(showProperties.getInfo())) {
                System.out.println(showProperties.getInfo());
            }else{
                System.out.println("Hello,浪飞yes....");
            }
        }

        return true;
    }
}

5> 構成インターセプター クラスを定義します -- WebConfig

package com.langfeiyes.mvc.config;

import com.langfeiyes.mvc.interceptor.ShowInfoInterceptor;
import com.langfeiyes.mvc.prop.ShowProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public ShowProperties showProperties(){
        return new ShowProperties();
    }

    @Bean
    public ShowInfoInterceptor showInfoInterceptor(){
        return new ShowInfoInterceptor();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(showInfoInterceptor())
                .addPathPatterns("/**");
    }
}

6> スターター エントリのスタートアップ クラス/構成クラスを構成する-ShowInfoAutConfig

package com.langfeiyes.mvc.config;


import com.langfeiyes.mvc.interceptor.ShowInfoInterceptor;
import com.langfeiyes.mvc.prop.ShowProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@ConditionalOnProperty(name = "mvc.interceptor.show", matchIfMissing = false)
@Configuration
@ComponentScan("com.langfeiyes.mvc")
public class ShowInfoAutConfig {

}

ConditionalOnProperty: The show attribute is required in the configuration file. 存在しない場合は、デフォルトで false になり、インターセプターが有効にならないことを示します。

ComponentScan: 指定されたパッケージをスキャンして、各コンポーネントのロードを実現します

7> スターター スターター エントリを構成します --resources/META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.langfeiyes.mvc.config.ShowInfoAutConfig

4.2.3 使用試験

1> プロジェクトを作成します: mvc-starter-demo

2> 関連する依存関係をインポートする

<!--父工程-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.2.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.langfeiyes.mvc</groupId>
        <artifactId>show-spring-boot-starter</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

3>インターセプトスターターを構成する

mvc:
  interceptor:
    info: hello,dafei...
    show: true

4> Web リクエストを開始するコントローラーを作成する


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "hello...fei~";
    }
}

5> プロジェクトを開始してテストする

package com.langfei.mvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

1: ブラウザを開き、アドレスバーにhttp://localhost:8080/helloと入力し、アクセスして効果を確認します。

2: コンソールを開き、インターセプターの出力を確認します

3: 構成ファイルの show を false に変更し、再度テストします。

mvc:
  interceptor:
    info: hello,dafei...
    show: false

4: 構成ファイルを直接削除して、もう一度やり直してください

5.スターターの原理とは

スターターを要求する原則について説明するには、まず SpringBoot の自動構成の原則を理解する必要があります。

SpringBoot 自動構成の原則

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

方言:

1> プロジェクトの開始後、SpringBoot は jar パッケージの下にあるすべての META-INF/spring.factories を検索し、事前設定された候補構成クラスを読み取ります。

2>次に、インポートされた依存関係/構成ファイルに従って、候補構成クラスによって設定された @ConditionalOnXxx 条件を一致させます

3> 候補構成クラスの事前設定条件が満たされると、候補構成クラスがアクティブになり、SpringBoot は構成クラスのすべての情報をすぐにアセンブルします。

画像ソース ネットワーク

 上の図は簡略化されています。

Starter の実装原理は、実際には SpringBoot の自動アセンブリの原理ですが、違いは、スターター自体の後続の構成クラスを手動でカスタマイズする必要があることです。

この場合の Starter 実行プロセスの例

SpringBoot---->spring.factories--->候補 ShowInfoAutConfig 構成クラス

--->Matching: @ConditionalOnClass/@ConditionalOnProperty--->アセンブル開始条件を満たす

--->@ComponentScan("com.langfeiyes.mvc")--->構成の読み込み: WebConfig--->Interceptor が正常に構成されました

6.スターター実戦ケース

6.1 要件の説明

要件: スターターをカスタマイズします。リクエスト マッピング メソッドがログに記録する必要がある場合は、@Log アノテーションを貼り付けるだけです。

要件: yml で mvc.log.enabled の値を構成して、有効にするか無効にするかを決定します。

mvc:
  log:
    enabled: true

6.2 実装手順

1> プロジェクトを作成します: log-aspect-spring-boot-starteer

2> 関連する依存関係をインポートする

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.2.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

</dependencies>

3> 受信リソース構成 JobProperties 構成クラスを定義する

1 つの暫定的なリソース構成があります: 有効

mvc:
  log:
    enabled: true

受入クラス

package com.langfeiyes.log.prop;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "mvc.log")
public class LogProperties {
    private boolean enabled;
    public boolean isEnabled() {
        return enabled;
    }
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

4> ログ注釈を定義する - @Log

@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
}

5> ログ アスペクト クラスを定義する -LogAspect

package com.langfeiyes.log.aspectj;

import com.langfeiyes.log.annotation.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
public class LogAspect{

    @Pointcut("@annotation(log)")
    public void webLog(Log log) {
    }

    @Before("webLog(log)")
    public void doBefore(JoinPoint joinPoint, Log log) {
        // 打印请求日志
        System.out.println("before" + log);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog(log)")
    public void doAfterReturning(Object ret, Log log) {
        // 打印响应结果日志
        System.out.println("doAfterReturning" + log);
    }
}

6> スターター エントリのスタートアップ クラス/構成クラスを構成する -LogAspectEnableAutoConfiguration

package com.langfeiyes.log.config;


import com.langfeiyes.log.aspectj.LogAspect;
import com.langfeiyes.log.prop.LogProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(LogProperties.class)
@ConditionalOnProperty(name = "mvc.log.enabled", matchIfMissing = true)
@ComponentScan("com.langfeiyes.log")
public class LogAspectEnableAutoConfiguration {

    @Bean
    public LogProperties logProperties(){
        return  new LogProperties();
    }

    @Bean
    public LogAspect logAspect(){
        return  new LogAspect();
    }
}

ConditionalOnProperty: The enabled attribute is required in the configuration file. 存在しない場合は、デフォルトで false になり、ログが有効にならないことを示します。

ComponentScan: 指定されたパッケージをスキャンして、各コンポーネントのロードを実現します

7> スターター スターター エントリを構成します --resources/META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.langfeiyes.log.config.LogAspectEnableAutoConfiguration

6.3 使用試験

1> プロジェクトを作成します: mvc-log-demo

2> 関連する依存関係をインポートする

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.2.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.langfeiyes.log</groupId>
        <artifactId>log-aspect-spring-boot-starteer</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>

3>ログスターターを構成する

mvc:
  log:
    enabled: true

4> Web リクエストを開始するコントローラーを作成する

package com.langfei.mvc.controller;

import com.langfeiyes.log.annotation.Log;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Log
    @GetMapping("/hello")
    public String hello(){
        return "ok-aspect";
    }
}

5> プロジェクトを開始してテストする

package com.langfei.mvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

1: ブラウザを開き、アドレスバーにhttp://localhost:8080/helloと入力し、アクセスして効果を確認します。

2: コンソールを開き、ログの出力を確認します

3: 構成ファイルの有効化を false に変更し、再度テストします。

mvc:
  log:
    enabled: false

4: 構成ファイルを直接削除して、もう一度やり直してください

6.4 アップグレード

@Log アノテーションを変換して、ロギング コンテンツをより充実させる

@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    //日志标题
    String title() default "";

    //操作类别
    OperType  type() default OperType.OTHER;
}

新しい型列挙型クラス

package com.langfeiyes.log.annotation;

/**
 * 业务操作类型
 */
public enum OperType
{
    /**
     * 其他
     */
    OTHER,
    /**
     * 查
     */
    QUERY,

    /**
     * 新增
     */
    INSERT,

    /**
     * 修改
     */
    UPDATE,

    /**
     * 删除
     */
    DELETE,
}

HelloController クラスを変換する

package com.langfei.mvc.controller;

import com.langfeiyes.log.annotation.Log;
import com.langfeiyes.log.annotation.OperType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "ok-aspect";
    }

    @Log(title = "员工查询", type = OperType.QUERY)
    @GetMapping("/emps/detail")
    public String detail(){
        return "ok-detail";
    }

    @Log(title = "员工添加", type = OperType.INSERT)
    @GetMapping("/emps/save")
    public String save(){
        return "ok-save";
    }
}

App クラスを開始して次のパスにアクセスし、結果を確認します。

http://localhost:8080/emps/detail --- 「現在の操作は次のとおりです: 従業員クエリ-QUERY

http://localhost:8080/emps/save --- "現在の実行操作は: 従業員の追加 - INSERT

以上で、spring-boot-starter スターターの紹介は終了です~

おすすめ

転載: blog.csdn.net/langfeiyes/article/details/130038798