亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
介面類別" >介面類別
實(shí)作類別" >實(shí)作類別
aop 攔截器" >aop 攔截器
測試類" >測試類
執(zhí)行結(jié)論 " >執(zhí)行結(jié)論
多切面的情況" >多切面的情況
代理失效場景" >代理失效場景
首頁 Java Java面試題 面試官:Spring Aop 常見註解和執(zhí)行順序

面試官:Spring Aop 常見註解和執(zhí)行順序

Aug 15, 2023 pm 04:32 PM
java java面試題

最近,我在給很多人做履歷修改和模擬面試的時(shí)候,有部分朋友和我回饋Spring AOP的面試題,今天就和大家來問。

Spring 一開始最強(qiáng)大的就是 IOC / AOP 兩大核心功能,我們今天一起來學(xué)習(xí) Spring AOP 常見註解和執(zhí)行順序。

Spring 面試核心點(diǎn):

IOC、AOP、Bean注入、Bean的生命週期、Bean的循環(huán)依賴

首先我們一起來回顧Spring Aop 中常用的幾個(gè)註解:

  • #@Before 前置通知:目標(biāo)方法之前執(zhí)行
  • @After 後置通知:目標(biāo)方法之後執(zhí)行(總是執(zhí)行)
  • #@AfterReturning 傳回之後通知:執(zhí)行方法結(jié)束先前執(zhí)行(異常不執(zhí)行)
  • @AfterThrowing 異常通知:出香異常後執(zhí)行
  • @Around 環(huán)繞通知:環(huán)繞目標(biāo)方法執(zhí)行

常見問題

1、你一定知道Spring ?, 那說說Aop 的去全部通知順序, Spring Boot 或Spring Boot 2 對aop 的執(zhí)行順序影響?

2、說說你在 AOP 中遇到的那些坑?

範(fàn)例程式碼

#下面我們先快速建立一個(gè)spring aop 的demo 程式來一起討論spring aop 中的一些細(xì)節(jié)。

設(shè)定檔

為了方便我直接使用spring-boot 進(jìn)行快速的項(xiàng)目搭建,大家可以使用idea 的spring-boot 專案快速建立功能,或是去start.spring.io 上面去快速建立spring-boot 應(yīng)用程式。

因?yàn)楸救私?jīng)常手動去網(wǎng)路上貼上一些依賴導(dǎo)致,依賴衝突服務(wù)啟動失敗等一些問題。

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group 'io.zhengsh'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
    maven { url 'https://repo.spring.io/milestone' }
    maven { url 'https://repo.spring.io/snapshot' }
}

dependencies {
    # 其實(shí)這里也可以不增加 web 配置,為了試驗(yàn)簡單,大家請忽略 
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-aop'
    
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

介面類別

#首先我們需要定義一個(gè)介面。我們這裡可以再來回顧一下JDK 的預(yù)設(shè)代理實(shí)現(xiàn)的選擇:

  • 如果目標(biāo)物件實(shí)現(xiàn)了接口,則預(yù)設(shè)採用JDK動態(tài)代理
  • 如果目標(biāo)物件沒有實(shí)現(xiàn)接口,則採用進(jìn)行動態(tài)代理
  • 如果目標(biāo)物件實(shí)現(xiàn)了接口,且強(qiáng)制Cglib,則使用cglib代理

這塊的邏輯在DefaultAopProxyFactory 大家有興趣可以去看看。

public interface CalcService {

    public int div(int x, int y);
}

實(shí)作類別

這裡我門就簡單一點(diǎn)做一個(gè)除法操作,可以模擬正常也可以很容易的模擬錯(cuò)誤。

@Service
public class CalcServiceImpl implements CalcService {

    @Override
    public int div(int x, int y) {
        int result = x / y;
        System.out.println("====> CalcServiceImpl 被調(diào)用了,我們的計(jì)算結(jié)果是:" + result);
        return result;
    }
}

aop 攔截器

#申明一個(gè)攔截器我們要為當(dāng)前物件增加@Aspect 和@Component ,筆者之前也是才踩過這樣的坑,只加了一個(gè)。

其實(shí)這塊我剛開始也不是很理解,但是我看了 Aspect 注解的定義我就清楚了

面試官:Spring Aop 常見註解和執(zhí)行順序

這里面根本就沒有 Bean 的定義。所以我們還是乖乖的加上兩個(gè)注解。

還有就是如果當(dāng)測試的時(shí)候需要開啟Aop 的支持為配置類上增加@EnableAspectJAutoProxy 注解。

其實(shí) Aop 使用就三個(gè)步驟:

  • 定義 Aspect 定義切面
  • 定義 Pointcut 就是定義我們切入點(diǎn)
  • 定義具體的通知,比如: @After, @Before 等。
@Aspect
@Component
public class MyAspect {

    @Pointcut("execution(* io.zhengsh.spring.service.impl..*.*(..))")
    public void divPointCut() {

    }

    @Before("divPointCut()")
    public void beforeNotify() {
        System.out.println("----===>> @Before 我是前置通知");
    }

    @After("divPointCut")
    public void afterNotify() {
        System.out.println("----===>> @After  我是后置通知");
    }

    @AfterReturning("divPointCut")
    public void afterReturningNotify() {
        System.out.println("----===>> @AfterReturning 我是前置通知");
    }

    @AfterThrowing("divPointCut")
    public void afterThrowingNotify() {
        System.out.println("----===>> @AfterThrowing 我是異常通知");
    }

    @Around("divPointCut")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object retVal;
        System.out.println("----===>> @Around 環(huán)繞通知之前 AAA");
        retVal = proceedingJoinPoint.proceed();
        System.out.println("----===>> @Around 環(huán)繞通知之后 BBB");
        return retVal;
    }
}

測試類

其實(shí)我這個(gè)測試類,雖然用了 @Test 注解,但是我這個(gè)類更加像一個(gè) main 方法把:如下所示:

面試官:Spring Aop 常見註解和執(zhí)行順序

執(zhí)行結(jié)論

結(jié)果記錄:spring 4.x, spring-boot 1.5.9

無法現(xiàn)在依賴,所以無法試驗(yàn)

我直接說一下結(jié)論:Spring 4 中環(huán)繞通知是在最里面執(zhí)行的

結(jié)果記錄:spring 版本5.3.15 springboot 版本2.6.3

面試官:Spring Aop 常見註解和執(zhí)行順序
img

多切面的情況

多個(gè)切面的情況下,可以通過@Order指定先后順序,數(shù)字越小,優(yōu)先級越高。如下圖所示:

面試官:Spring Aop 常見註解和執(zhí)行順序

代理失效場景

下面一種場景會導(dǎo)致 aop 代理失效,因?yàn)槲覀冊趫?zhí)行 a 方法的時(shí)候其實(shí)本質(zhì)是執(zhí)行 AServer#a 的方法攔截器(MethodInterceptor)鏈, 當(dāng)我們在 a 方法內(nèi)直接執(zhí)行b(), 其實(shí)本質(zhì)就相當(dāng)于 this.b() , 這個(gè)時(shí)候由執(zhí)行 a方法是調(diào)用到 a 的原始對象相當(dāng)于是 this 調(diào)用,那么會導(dǎo)致 b() 方法的代理失效。這個(gè)問題也是我們開發(fā)者在開發(fā)過程中最常遇到的一個(gè)問題。

@Service
public class AService {
    
    public void a() {
        System.out.println("...... a");
        b();
    }
    
    public void b() {
        System.out.println("...... b");
    }

}

以上是面試官:Spring Aop 常見註解和執(zhí)行順序的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
VSCODE設(shè)置。 JSON位置 VSCODE設(shè)置。 JSON位置 Aug 01, 2025 am 06:12 AM

settings.json文件位於用戶級或工作區(qū)級路徑,用於自定義VSCode設(shè)置。 1.用戶級路徑:Windows為C:\Users\\AppData\Roaming\Code\User\settings.json,macOS為/Users//Library/ApplicationSupport/Code/User/settings.json,Linux為/home//.config/Code/User/settings.json;2.工作區(qū)級路徑:項(xiàng)目根目錄下的.vscode/settings

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務(wù),必須先關(guān)閉自動提交模式,再執(zhí)行多個(gè)操作,最後根據(jù)結(jié)果提交或回滾;1.調(diào)用conn.setAutoCommit(false)以開始事務(wù);2.執(zhí)行多個(gè)SQL操作,如INSERT和UPDATE;3.若所有操作成功則調(diào)用conn.commit(),若發(fā)生異常則調(diào)用conn.rollback()確保數(shù)據(jù)一致性;同時(shí)應(yīng)使用try-with-resources管理資源,妥善處理異常並關(guān)閉連接,避免連接洩漏;此外建議使用連接池、設(shè)置保存點(diǎn)實(shí)現(xiàn)部分回滾,並保持事務(wù)盡可能短以提升性能。

在Java的掌握依賴注入春季和Guice 在Java的掌握依賴注入春季和Guice Aug 01, 2025 am 05:53 AM

依賴性(di)IsadesignpatternwhereObjectsReceivedenciesenciesExtern上,推廣looseSecouplingAndEaseerTestingThroughConstructor,setter,orfieldInjection.2.springfraMefringframeWorkSannotationsLikeLikeLike@component@component,@component,@service,@autowiredwithjava-service和@autowiredwithjava-ligatiredwithjava-lase-lightike

如何使用Java的日曆? 如何使用Java的日曆? Aug 02, 2025 am 02:38 AM

使用java.time包中的類替代舊的Date和Calendar類;2.通過LocalDate、LocalDateTime和LocalTime獲取當(dāng)前日期時(shí)間;3.使用of()方法創(chuàng)建特定日期時(shí)間;4.利用plus/minus方法不可變地增減時(shí)間;5.使用ZonedDateTime和ZoneId處理時(shí)區(qū);6.通過DateTimeFormatter格式化和解析日期字符串;7.必要時(shí)通過Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應(yīng)優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

了解Java虛擬機(jī)(JVM)內(nèi)部 了解Java虛擬機(jī)(JVM)內(nèi)部 Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome無法打開本地文件 Google Chrome無法打開本地文件 Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

比較Java框架:Spring Boot vs Quarkus vs Micronaut 比較Java框架:Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

前形式攝取,quarkusandmicronautleaddueTocile timeProcessingandGraalvSupport,withquarkusoftenpernperforminglightbetterine nosserless notelless centarios.2。

了解網(wǎng)絡(luò)端口和防火牆 了解網(wǎng)絡(luò)端口和防火牆 Aug 01, 2025 am 06:40 AM

NetworkPortSandFireWallsworkTogetHertoEnableCommunication whereSeringSecurity.1.NetWorkPortSareVirtualendPointSnumbered0-655 35,with-Well-with-Newonportslike80(HTTP),443(https),22(SSH)和25(smtp)sindiessingspefificservices.2.portsoperateervertcp(可靠,c

See all articles