Spring AOP pre-notification and post-notification

Source: Internet
Author: User

Spring AOP
The most complete and popular AOP framework in the Aspectj:java community
In versions above Spring2.0, you can use AOP based on ASPECTJ annotations or XML-based configuration


Enable ASPECTJ annotation support in spring
To use ASPECTJ annotations in a spring application, you must include the AspectJ class library under Classpath: Aopalliance.jar, Aspectj.weaver.jar, and Spring-aspects.jar
Add an AOP schema to the <beans> root element.
To enable ASPECTJ annotation support in the spring IOC container, as long as an empty XML element is defined in the early Bean configuration file <aop:aspectj-autoproxy>
When the spring IOC container detects the <aop:aspectj-autoproxy> element in the bean configuration file, the agent is automatically created for the bean that matches the ASPECTJ slice


Declaring slices with ASPECTJ annotations
To declare a ASPECTJ slice in spring, you only need to declare the slice as a bean instance in the IOC container. When AspectJ facets are initialized in the spring IOC container, the spring IOC container creates proxies for those beans that match the aspectj facets
In ASPECTJ annotations, facets are just a Java class with @aspectj annotations
Notifications are simple Java methods that annotate some kind of annotation
ASPECTJ supports 5 types of notification annotations:
@Before: Forward notification, returned before method execution
@After: Post notification, executed after method execution
@AfterRunning: Returns a notification that executes after the method returns the result
@AfterThrowing: Exception notification, after the method throws an exception
@Around: Surround notifications, execute around methods

Writing AspectJ pointcut expressions using method signatures
The most typical pointcut expression matches various methods according to the signature of the method:
-execution * com.yl.spring.aop.arithmeticcalculator.* (..): Matches all methods declared in Arithmeticcalculator, the first * represents any modifier and any return value, the second * Represents any method,.. Match any number of parameters. If the target class and interface are in the same package as the plane, the package name can be omitted.
-execution public * arithmeticcalculator.* (..): All publicly-owned methods matching the Arithmeticcalculator interface
-execution public Double arithmeticcalculator.* (..): A method that returns the value of a double type in a matching arithmeticcalculator
-execution public double arithmeticcalculator.* (double, ...): matches the first argument to a method of type double. Match any number of arguments of any type
-execution public double arithmeticcalculator.* (double, double): A method that matches the type of the parameter type double,double

Post notification
The post notification is executed after the connection point is completed, that is, when the connection point returns a result or throws an exception, the following post notification records the termination of the method.
A slice can include one or more notifications

Loggingaspect.java

1  PackageCom.yl.spring.aop.impl;2 3 Importjava.util.Arrays;4 Importjava.util.List;5 6 ImportOrg.aspectj.lang.JoinPoint;7 ImportOrg.aspectj.lang.annotation.After;8 ImportOrg.aspectj.lang.annotation.Aspect;9 ImportOrg.aspectj.lang.annotation.Before;Ten Importorg.springframework.stereotype.Component; One  A //This class is declared as a tangent: the class needs to be put into an IOC container and then declared as a slice. - @Aspect - @Component the  Public classLoggingaspect { -      -     //declares that the method is a pre-notification: Executes before the target method starts -     //@Before ("Execution (public int com.yl.spring.aop.impl.ArithmeticCalculatorImpl.add (int, int))" ) +@Before ("Execution (* com.yl.spring.aop.impl.*.* (..))") -      Public voidBeforemethod (Joinpoint joinpoint) { +String MethodName =joinpoint.getsignature (). GetName (); Alist<object> args =arrays.aslist (Joinpoint.getargs ()); atSystem.out.println ("the method" + MethodName + "begins with" +args); -     } -     //Post notification: Notification of execution after the target method executes (regardless of whether an exception occurs) -     //The results of the target method execution are not yet accessible in the post-notification -@After ("Execution (* com.yl.spring.aop.impl.*.* (..))") -      Public voidAftermethod (Joinpoint joinpoint) { inString MethodName =joinpoint.getsignature (). GetName (); -list<object> args =arrays.aslist (Joinpoint.getargs ()); toSystem.out.println ("the method" + MethodName + "End with" +args); +     } -      the}

Configuration file Applicationcontext.xml:

1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Beansxmlns= "Http://www.springframework.org/schema/beans"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"5 Xmlns:context= "Http://www.springframework.org/schema/context"6 xsi:schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 7 Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.1.xsd ">9     Ten     <!--Configure automatic scanning of packages - One     <Context:component-scanBase-package= "Com.yl.spring.aop.impl"></Context:component-scan> A      -     <!--make ASPECTJ annotations work: Automatically generate proxy objects for matching classes - -     <Aop:aspectj-autoproxy></Aop:aspectj-autoproxy> the      - </Beans>

Test class:

1  PackageCom.yl.spring.aop.impl;2 3 ImportOrg.springframework.context.ApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6  Public classMain {7      Public Static voidMain (string[] args) {8         9ApplicationContext CTX =NewClasspathxmlapplicationcontext ("Applicationcontext.xml");Ten          OneArithmeticcalculator arithmeticcalculator = Ctx.getbean (arithmeticcalculator.class); A          -         intresult = Arithmeticcalculator.add (4, 6); -SYSTEM.OUT.PRINTLN ("Result:" +result); the          -result = Arithmeticcalculator.mul (4, 6); -SYSTEM.OUT.PRINTLN ("Result:" +result); -     }  +}

Spring AOP pre-notification and post-notification

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.