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 的定義。所以我們還是乖乖的加上兩個注解。
還有就是如果當(dāng)測試的時(shí)候需要開啟Aop 的支持為配置類上增加@EnableAspectJAutoProxy
注解。
其實(shí) Aop 使用就三個步驟:
定義 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í)我這個測試類,雖然用了 @Test 注解,但是我這個類更加像一個 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

多切面的情況
多個切面的情況下,可以通過@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() , 這個時(shí)候由執(zhí)行 a方法是調(diào)用到 a 的原始對象相當(dāng)于是 this 調(diào)用,那么會導(dǎo)致 b() 方法的代理失效。這個問題也是我們開發(fā)者在開發(fā)過程中最常遇到的一個問題。
@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)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

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.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

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

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
