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

Table of Contents
Interface class" >Interface class
Implementation class" >Implementation class
aop interceptor" >aop interceptor
測試類" >測試類
執(zhí)行結(jié)論 " >執(zhí)行結(jié)論
多切面的情況" >多切面的情況
代理失效場景" >代理失效場景
Home Java JavaInterview questions Interviewer: Spring Aop common annotations and execution sequence

Interviewer: Spring Aop common annotations and execution sequence

Aug 15, 2023 pm 04:32 PM
java java interview questions

Recently, 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 注解的定義我就清楚了

Interviewer: Spring Aop common annotations and execution sequence

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

Interviewer: Spring Aop common annotations and execution sequence

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

Interviewer: Spring Aop common annotations and execution sequence
img

多切面的情況

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

Interviewer: Spring Aop common annotations and execution sequence

代理失效場景

下面一種場景會導(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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

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

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

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.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

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

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

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;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

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.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

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.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

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

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

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

See all articles