Interviewer: Spring Aop common annotations and execution sequence
Aug 15, 2023 pm 04:32 PMRecently, when I was revising resumes and doing mock interviews for many people, some friends gave me feedback on Spring AOP interview questions, and I will ask them today.
The most powerful thing about Spring at the beginning is the two core functions of IOC/AOP. Today we will learn about the common annotations and execution sequence of Spring AOP.
Spring interview core points:
IOC, AOP, Bean injection, Bean life cycle, Bean circular dependency
First of all we Let’s review some commonly used annotations in Spring Aop:
@Before
Pre-notification: Execute before the target method-
@After
Post notification: executed after the target method (always executed) @AfterReturning
Post notification: execution method ends Execute before (not executed if exception occurs)@AfterThrowing
Exception notification: Execute after exception@Around
Around notification: Around target method execution
##FAQ
1. You must know Spring. Let’s talk about the order of all notifications of Aop. How does Spring Boot or Spring Boot 2 affect the execution order of aop? 2. Tell us about the pitfalls you encountered in AOP?Sample code
Let’s quickly build a demo program of spring aop to discuss spring together Some details in aop.
Configuration file
For the convenience, I directly use spring-boot for quick projects To build, you can use the spring-boot project quick creation function of idea, or go to start.spring.io
to quickly create a spring-boot application.
Because I often manually post some dependencies on the Internet, there are some problems such as dependency conflicts and service startup failure.
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() }
Interface class
First we need to define an interface. Here we can review the choice of JDK's default proxy implementation:
If the target object implements the interface, the JDK dynamic proxy is used by default If the target object does not implement the interface, use dynamic proxy If the target object implements the interface and Cglib is forced, use cglib proxy
The logic of this piece is in DefaultAopProxyFactory
If you are interested, you can take a look.
public interface CalcService { public int div(int x, int y); }
Implementation class
Here we will simply do a division operation, which can simulate normal or easy errors.
@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 interceptor
#To declare an interceptor, we need to add @Aspect and @Component to the current object. The author has only stepped on it before. Only one such pit has been added.
其實(shí)這塊我剛開始也不是很理解,但是我看了 Aspect 注解的定義我就清楚了

這里面根本就沒有 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 方法把:如下所示:

執(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

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

代理失效場景
下面一種場景會導(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"); } }
The above is the detailed content of Interviewer: Spring Aop common annotations and execution sequence. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
