Spring Basic Series--AOP Practice

Source: Internet
Author: User
Tags aop throwable

Original works, yes, but please mark the source address: www.cnblogs.com/V1haoge/p/9615720.html

The purpose of this article is to briefly explain the use of spring AOP.

It is recommended to use Idea + Spring Boot.

Create a new Spring Boot project and select the Aspect feature.

After creation, the Pom file is as follows:

1<?xml version= "1.0" encoding= "UTF-8"?>2<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"3xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >4<modelVersion>4.0.0</modelVersion>5 6<groupId>com.example</groupId>7<artifactId>spring-aspect-demo</artifactId>8<version>0.0.1-SNAPSHOT</version>9<packaging>jar</packaging>Ten  One<name>spring-aspect-demo</name> A<description>demo Project forSpring boot</description> -  -<parent> the<groupId>org.springframework.boot</groupId> -<artifactId>spring-boot-starter-parent</artifactId> -<version>2.0.4.RELEASE</version> -<relativePath/> <!--lookup parent from repository to +</parent> -  +<properties> A<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> at<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> -<java.version>1.8</java.version> -</properties> -  -<dependencies> -<dependency> in<groupId>org.springframework.boot</groupId> -<artifactId>spring-boot-starter-aop</artifactId> to</dependency> +  -<dependency> the<groupId>org.springframework.boot</groupId> *<artifactId>spring-boot-starter-test</artifactId> $<scope>test</scope>Panax Notoginseng</dependency> -</dependencies> the  +<build> A<plugins> the<plugin> +<groupId>org.springframework.boot</groupId> -<artifactId>spring-boot-maven-plugin</artifactId> $</plugin> $</plugins> -</build> -  the  -</project>

Then we create the target classes and methods:

1  PackageCom.example.springaspectdemo;2 3 Importorg.springframework.stereotype.Component;4 5 @Component6  Public classAspectdemo {7      PublicInteger Test (String s) {8System.out.println ("Target Method execution-" +s);9         return123321;Ten     } One}

The main thing in the code above is the @component annotation, which scans the target class into the spring container.

Below we create the slice class:

1  PackageCom.example.springaspectdemo;2 3 ImportOrg.aspectj.lang.JoinPoint;4 ImportOrg.aspectj.lang.ProceedingJoinPoint;5 Importorg.aspectj.lang.annotation.*;6 Importorg.springframework.stereotype.Component;7 8 @Aspect9 @ComponentTen  Public classAspecttest { One  A@Pointcut (value = "Execution (* *.test (..)) && args (s) ") -      Public voidPC (String s) { -SYSTEM.OUT.PRINTLN ("Tangent execution"); the     } -  A@Before ("PC (s)")) at      Public voidBeforetest (joinpoint jp,string s) { -System.out.println ("Pre-notification-arg=" +s); -     } -  -@After ("PC (s)")) -      Public voidAftertest (String s) { inSystem.out.println ("Post endpoint notification-arg=" +s); -     } to  +@AfterReturning (pointcut = "PC (s)", returning = "I") -      Public voidAfterreturningtest (Object i,string s) { theSystem.out.println ("Back Return notification-return=" +i+ "-arg=" +s); *     } $ Panax Notoginseng@AfterThrowing (pointcut = "PC (s)", throwing = "E") -      Public voidAfterthrowingtest (Exception e,string s) { theSystem.out.println ("Post-exception notification-" +e.getmessage () + "-arg=" +s); +     } A  the@Around ("PC (s)")) +      Public voidAroundtest (proceedingjoinpoint jp,string s) { -System.out.println ("Surround Front notification-arg=" +s); $object[] OS =Jp.getargs (); $s = "Caocao"; -Os[0] =s; -         Try { the jp.proceed (OS); -}Catch(Throwable throwable) {Wuyi throwable.printstacktrace (); the         } -SYSTEM.OUT.PRINTLN ("Surround post notification-arg=" +s); Wu     } -}

To create a test case:

1  PackageCom.example.springaspectdemo;2 3 Importorg.junit.Test;4 ImportOrg.junit.runner.RunWith;5 Importorg.springframework.beans.factory.annotation.Autowired;6 Importorg.springframework.boot.test.context.SpringBootTest;7 ImportOrg.springframework.context.annotation.EnableAspectJAutoProxy;8 ImportOrg.springframework.test.context.junit4.SpringRunner;9 Ten@RunWith (Springrunner.class) One @SpringBootTest A @EnableAspectJAutoProxy -  Public classspringaspectdemoapplicationtests { - @Autowired the     PrivateAspectdemo Aspectdemo; -  - @Test -      Public voidaspeccttest () { +Aspectdemo.test ("Huahua"); -     } +}

Execution Result:

Surround the front notification-arg=Huahua pre-notification -arg=Caocao target method Execution -Caocao surround post notification -arg=Caocao post endpoint notification -arg= Caocao back Notification -return =null-arg=caocao

Key analysis:

1, the back of the return notification is after the target code execution, the return of the results after execution, you can process the returned results, but note that it cannot be combined with the surround notification to the same target method, otherwise it will not be able to get the return value, as in the above example, the result of the last row of NULL, Represents the return value, and if the part of the wrapping notification is commented out, the correct result can be returned.

2. The return value type of the back-return notification must be a reference type or a wrapper type, not the original type, otherwise an error will be returned and the type mismatch.

3, we can modify the parameters of the target method, but only in the surround notification, the first parameter in the wrapping notification must be proceedjoinpoint, it is the subclass of Joinpoint, through its Getargs method can get to call the target method parameter list, You can modify it, and then execute the proceed method with parameters, passing the new parameter list to the target method. And we can see from the above results that the front part of the surround notification is executed before all other notifications, then it modifies the parameters to be used for all subsequent notifications. As in the example, we changed the parameter "Huahua" to "Caocao" in the front part of the surround notification, and all the parameters obtained in the subsequent notification and target methods became "Caocao".

4. Exception notification does not just catch the exception in the target method, but also the exception that occurs in other notifications on the same method. Therefore, the Afterreturning notification method is not executed once an exception occurs. If the target method performs normally, but an exception occurs in the afterreturning, the Afterreturning notification method and the Afterthrowing notification method are executed simultaneously.

5, we can also see the execution order of each notification from the above execution result:

Surround notification PRE----> Pre-Notification---> Target method---> Surround notification post---> Back end notification---> BACK notification---> POST exception notification

6, for the above implementation of a little supplement:

That is, if an exception occurs in the front part of the surround notification, then only the last exception notification will be triggered and the rest will not be executed except that the post endpoint notification is bound to execute.

If there is an exception in the execution order of the 5th, then the notification in front of it will be executed normally, and the exception notification will be triggered when the subsequent end-point notification is bound to execute.

There is an exception to this, which is a pre-notification, where the exception to the pre-notification is not caught by the post-exception notification when both the forward notification and the Surround Notification Act on a target method.

7. As mentioned above, it is recommended not to use surround notice and other notices. Because surround notifications cause some anomalies, some of the features of other notifications become invalid.

You can use the code above to modify the test!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.