Spring AOP Programming--aspectj annotation Method (4)

Source: Internet
Author: User
Tags mul string format

1. Introduction to AOP

AOP (aspect-oriented programming, facet-oriented programming): A new methodology that complements traditional OOP (object-oriented programming, object-oriented programming).

The main programming objects of AOP are facets (aspect), while facets are modular crosscutting concerns.

When you apply AOP programming, you still need to define public functionality, but you can clearly define where and how this function is applied, without having to modify the affected classes. This way the crosscutting concerns are modularized into special objects (facets).

Benefits of AOP:

---each thing logic in one place, code is not scattered, easy to maintain and upgrade

---Business module is more concise and contains only the core business code.

2. Terminology and graphical representations of AOP

Facets (Aspect): Special objects that are modularized by crosscutting concerns (functions that span multiple modules of the application)

Notification (Advice): The work that the slice must complete

Target: The object being notified

Proxy: An object created after the notification is applied to the target object

Connection point (Joinpoint): A specific location for a program to execute, such as before a method call to a class, after a call, after a method throws an exception, and so on. The connection point is determined by two information: The program execution point represented by the method, and the orientation represented by the relative point. For example, the connection point before the Arithmethiccalculator#add () method executes, the execution point is Arithmethiccalculator#add (), and the position is before the method executes.

Tangency Point (pointcut): Each class has multiple connection points: for example, all methods of arithmethiccalculator are actually connection points, that is, the connection point is an objective transaction in the program class. AOP navigates to a specific connection point through a pointcut. Analogy: A connection point is equivalent to a record in a database, and a tangent is equivalent to a query condition. Tangency and connection points are not a one-to-one relationship, a pointcut matches multiple connection points, and the pointcut is described by the Org.springframework.aop.Pointcut interface, which uses classes and methods as query criteria for connection points.

Notice:

  pre-notification (before advice): executed before the pointcut.

  Post notification (after returning advice): executes the notification after the Pointcut execution is complete. Executes regardless of whether an exception is thrown. The results returned by the method cannot be accessed in the post-notification

  surround notification (around advice): surrounds the pointcut, invoking the method before and after the custom behavior is completed.

  exception notification (after throwing advice): executes the notification after the pointcut throws an exception.

method One, aspectj annotation :

1, need to introduce a

2, Arithmeticcalculator.java

1PackageCom.proc;23Publicinterface Arithmeticcalculator { 4 int Add (int I, int J); 5 int Sub (int I, int J); 6 7 int mul (int I, int J); int div (int I, int J); 9}             

3, Arithmeticcalculatorimpl.java

1PackageCom.proc;2ImportOrg.springframework.stereotype.Component;345 @Component ("Arithmeticcalculator")6PublicClass ArithmeticcalculatorimplImplementsarithmeticcalculator{7Publicint Add (int I,Intj) {8int result = i +J9ReturnResult10}1112Publicint Sub (int I,Intj) {13int result = i-J14ReturnResult15}1617Publicint Mul (int I,Intj) {18 int result = I * J;19 return Result;20 }21 22" Span style= "COLOR: #0000ff" >public int div (int I, int j) {23 int result = I/ J; return Result; }26}        

4, Loggingaspect.java

1PackageCom.proc;23ImportOrg.aspectj.lang.JoinPoint;4ImportOrg.aspectj.lang.annotation.Aspect;5ImportOrg.aspectj.lang.annotation.Before;6ImportOrg.springframework.stereotype.Component; 7  8  @Aspect  9  @Component 10 public class Loggingaspect {11 12 @Before ("Execution (* * * (int,int))" ) 13 public void Beforemethod (Joinpoint point) {14 System.out.println ("Executing method:" +point.getsignature (). GetName ());  }16}       

This is a log slice class, which is first a bean in the IOC, which is managed by @component the bean into a container, and then @aspect declares that this is a slice.

@Before is the time to notify when a method is called. Inside the string format is execution (the access modifier returns the type package name.) The class name. Method name (parameter type ...).

Beforemethod is a method that specifies a facet execution, and the method name can be arbitrarily specified. You can also specify a parameter for a joinpoint connection point without parameters.

Configuration

<base-package/><aop:aspectj-autoproxy></aop:aspectj-autoproxy >      

Aop:aspectj-autoproxy: Make @aspect annotations Effective

Test code:

1 ApplicationContext ctx=new Classpathxmlapplicationcontext ("Applicationcontext.xml");  2 Arithmeticcalculator calc= (arithmeticcalculator) Ctx.getbean ("Arithmeticcalculator");  3 System.out.println (Calc.add (3, 5));  4 System.out.println (Calc.sub (3, 55 System.out.println (Calc.mul (6, 2        

Output results

Executing method Add8 Executing method sub-2 executing method mul12 executing method div3  

The above method is used for the pre-notification. Let's talk about post notifications, return notifications, exception notifications, and surround notifications

☆ Post Notification

  The post notification executes regardless of whether the method throws an exception. The returned result cannot be accessed in the post notification because an exception may occur and there is no return value

1 @After ("Execution (* *. * * (Int,int))")void Aftermethod (joinpoint point) {3 System.out.println (" Method execution Ends: "+point.getsignature (). GetName ()); 4}     

☆ Return Notification

  When there is an exception to the method, the return notification is not performed and the return notification can only be performed at the end of the method's normal execution. In the result notification, the parameter returning is used to specify the name of the receiving returned result object, which is passed directly to the corresponding parameter in the following method

1 @AfterReturning (value= "Execution (* * * * (Int,int))", returning= "RetVal")void Afterreturningmethod ( Joinpoint point,object retVal) {3 System.out.println ("Method:" +point.getsignature (). GetName () + "execution Result:" +RetVal) ; 4}     

☆ Exception Notification

Return exception notification is performed when the method has an exception

1 @AfterThrowing (value= "Execution (* * * * (Int,int))", throwing= "ex")void Afterthrowingmethod (joinpoint Point,exception ex) {3 System.out.println ("Execute Method:" +point.getsignature (). GetName () + "Exception occurred:" +Ex.getmessage () ); 4}     

Note: When you specify an exception type, you can only catch exceptions of that type or subtype. For example, specifying a NullPointerException exception can only catch a null pointer exception, so we can specify the parent type of the exception.

☆ Surround Notice

 Surround notification is a powerful, but relatively complex, notification that we don't usually use

1 @Around ("Execution (* * * * (int,int))")2PublicObject Aroundmethod (Proceedingjoinpoint point) {34 SYSTEM.OUT.PRINTLN ("Surround Notification:" +Point.getsignature (). GetName ());5 Object result=Null;6//This is the equivalent of a pre-notification7Try{8//Execution method9 result=Point.proceed ();10// This is equivalent to the result notification 11} catch (Throwable e) {12 // This is equivalent to exception notification 13  E.printstacktrace (); 14 15 }16 // This is equivalent to the post notification  System.out.println ("Surround Notice:" +point.getsignature (). GetName ());  return Result;                 

Note: The surround notification requires a return value of Point.proceed () to execute the method and provide a return value

Spring AOP Programming--aspectj annotation Method (4)

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.