Spring uses AOP to implement front, surround, exception notifications, annotations

Source: Internet
Author: User
Tags string find string methods

The main contents of this section: 1. Spring AOP Pre-notification case 2. Spring AOP Surround Notification case 3. Spring AOP Exception Notification case 4. Spring AOP Annotated use case

AOP is the abbreviation for Aspect oriented programming, meaning aspect-oriented programming, and AOP is actually the continuation of GOF design pattern.

Some terms about spring AOP

    • Facets (Aspect): In spring AOP, facets can be implemented using generic classes or @aspect annotations (@AspectJ styles) in ordinary classes
    • Connection point (Joinpoint): A connection point in spring AOP represents the execution of a method
    • Notification (Advice): An action performed on a particular connection point (joinpoint) of a slice. Notifications are available in various types, including notifications such as "Around", "before", and "after". Many AOP frameworks, including spring, are notification models with interceptors and maintain a link-centric interceptor chain.
    • Pointcut (Pointcut): Defines a method or set of methods that, when executed, can generate notifications, and spring uses the ASPECTJ pointcut syntax by default.

Notification type

    • Pre-notification (@Before): A notification that is executed before a connection point, but this notification does not prevent execution before the connection point (unless it throws an exception)
    • Notification after return (@AfterReturning): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally
    • Notification after an exception is thrown (@AfterThrowing): The method throws an exception when the notification is executed when exiting
    • Post Notification (@After): notification to be executed when a connection point exits (whether it is a normal return or an abnormal exit)
    • Surround Notification (@Around): A notification that encloses a connection point, such as a method call. This is the most powerful type of notification, and wrapping notifications can perform custom behavior before and after a method call, and it also chooses whether to continue executing the connection point or return directly to their own return value or throw an exception to end the execution

Spring implements AOP by relying on the JDK dynamic agent and the Cglib proxy implementation.     The following is a brief description of the JDK dynamic agent and the Cglib proxy: Its proxy object must be an implementation of an interface that accomplishes the proxy to the target object by creating an implementation class of an interface during runtime. Cglib Proxy: The implementation principle is similar to the JDK dynamic proxy, except that the proxy object that it generates during runtime is a subclass of the target class extension. Cglib is an efficient code generation package that relies on ASM (open source Java bytecode editing class library) to operate bytecode implementations that are more robust than JDK.

In spring, the interface will implement proxy proxy object in the way of JDK, when there is no interface, the Prixy proxy object will be implemented in Cglib.

1 Spring AOP Pre-notification Case 1.1 issue

With spring AOP pre-notification, the user's action log is logged before each method in the controller is accessed.

1.2 Solutions

Spring AOP Use steps:

1.3 Steps

The implementation of this case needs to follow the steps below.

Step One: Create a controller and create a new project SPRINGAOP.

To import the jar package for the spring environment:

If there is no jar package, then go up to the next. : Http://yunpan.cn/cdXTcJtZfJqQk access Password 6c96

Create an employee business controller Empcontroller, and implement employee queries with the following code:

PackageCom.souvc.controller;ImportOrg.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping; @Controller @requestmapping ("/emp") public class Empcontroller { /** * Query Employee * /@RequestMapping ("/findemp.do") public< c12> String Find () { /// mock query Employee Data System.out.println ("Query employee data, send to List page.") ); return "emp/emp_list.jsp";}}             

Step Two: Create facet components

Create the Facet component Operatelogger and create a method for recording the user action log in this class, with the following code:

PackageCom.souvc.aspect;ImportJava.text.SimpleDateFormat;ImportJava.util.Date;ImportOrg.aspectj.lang.ProceedingJoinPoint;Importorg.aspectj.lang.annotation.AfterThrowing;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;import Org.aspectj.lang.annotation.before;import Org.springframework.stereotype.component; /** * a facet component for logging, demonstrating the various notification types of spring AOP. */public class Operatelogger {/** * pre-notification, post-notification, final notification using method */public void Log1 () { // log System.out.println ("Record user action information" ); }} 

Step Three: Declaration facet components

In Applicationcontext.xml, declare this aspect component, the key code is as follows:

     <!--declaration aspects components--      class= "Com.souvc.aspect.OperateLogger"/>

Step four: Effect the aspect component on the target component

In Applicationcontext.xml, the key code for all the methods of all classes under the Com.souvc.controller package is to act on the declared aspect component, as follows:

<!--claims aspect components--    class= "Com.souvc.aspect.OperateLogger"/>        <!--configuring AOP--and    <AOP: config>        <aop:aspect ref= "Operatelogger" >            <aop:before method= "Log1" pointcut= "within                 ( Com.souvc.controller. *) "/>        </aop:aspect>     

Step Five: Test

Create a JUnit test class Testempcontroller and add a method for testing the employee, with the following code:

PackageCom.souvc.test;ImportOrg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;import Com.souvc.controller.EmpController;  Public class Testempcontroller { /** * Test Query Employee * /@Test public  void test1 () {Applica Tioncontext CTX = new classpathxmlapplicationcontext ("Applicationcontext.xml"); Empcontroller ctl = Ctx.getbean (empcontroller.  Class); Ctl.find (); }}

To perform this test method, the console output effect:

--Record user action information to query employee data and send to List page.

It can be seen that the method of logging the facet component was performed before the Empcontroller.find () method was executed, because the method was implemented using AOP object-oriented thinking, so no change to the controller class was necessary.

Step Six: Expand

The use of the post-notification and final notification is exactly the same as the pre-notification, requiring only the aop:before to be changed to aop:after-returning and aop:after when configuring AOP. Try to change the pre-notification type to a post-notification, a final notification, and execute the test method to see the console's output.

The source code is as follows: HTTP://YUNPAN.CN/CDXHDCB4DQMQV access password 0f0b

2 Spring AOP Surround Notification Case 2.1 issue

With spring AOP surround notifications, logs of the user's operations are logged before each method in the controller is accessed.

2.2 Solutions

Spring AOP Use steps:

2.3 Steps

The implementation of this case needs to follow the steps below.

Step One: Create facet components

The multiplexing facet component Operatelogger, in which a new logging method is created in this class log2, the code is as follows:

PackageCom.souvc.aspect;ImportJava.text.SimpleDateFormat;ImportJava.util.Date;ImportOrg.aspectj.lang.ProceedingJoinPoint;Importorg.aspectj.lang.annotation.AfterThrowing;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;ImportOrg.springframework.stereotype.Component;/*** The aspect component for logging, demonstrating the various notification types of spring AOP.*/PublicClassOperatelogger {/*** Pre-notification, post-notification, final notification using the method*/PublicvoidLog1 () {//Logging System.out.println ("User Action information"); }/*** methods used to surround notifications*/Public Object log2 (Proceedingjoinpoint p)ThrowsThrowable {//The class name of the target component String ClassName =P.gettarget (). GetClass (). GetName ();//Called method name, String methods =P.getsignature (). GetName ();//Current system time String date =new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss" ). Format ( Span style= "color: #0000ff;" >new Date ()); // spelling log information String msg = "-User in" + date + ", executed" + className + "." + Method + "()" ; // log // method to execute the target Component Object obj =  P.proceed (); // After calling the target component business method, you can also do some business processing System.out.println ("-- After calling the target component business method ... "); return obj;}}       

Step Two: Declaration facet components

This step can be omitted because the facet component of the reuse has already been declared.

Step three: Effect the aspect component on the target component

In Applicationcontext.xml, the Log2 method for declaring facet components, the key code is as follows:

<aop:aspect ref= "Operatelogger" >   <aop:around method= "log2" pointcut= "within                 ( Com.souvc.controller. *) "/> </aop:aspect>

Step Four: Test

Execute the test method Testempcontroller.test1 (), the console output effect such as:

-User 2015-08-17 05:59:13, executed a com.souvc.controller.EmpController.find () query employee data, sent to the list page .--> call the target component business method ...

Project source code as follows: HTTP://YUNPAN.CN/CDXAI6KMCVVP3 access password F4CD
Http://www.cnblogs.com/liuhongfeng/p/4736947.html

Spring uses AOP to implement front, surround, exception notification, annotations (GO)

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.