Summary and case of "Spring" AOP based on ASPECTJ annotations

Source: Internet
Author: User

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

In addition to supporting schema configuration for AOP, spring supports annotation methods: using @aspectj-style facet declarations. Import the required packages: Aspectjweaver.jar, Aopalliance-1.0.jar

I. Basic methods of Use
1.1. Enable support for @aspectj

Spring does not support @aspectj-style facet declarations by default, in order to support the need to use the following configuration:

<!--start @aspectj support--><!--proxy-target-class default "false" and change to "ture" using cglib dynamic Agent--  <AOP: Aspectj-autoproxy proxy-target-class= "false"/>
This allows spring to discover @aspectj-style facets and apply facets to the target object.

1.2. Declaring slices

@AspectJ-style declarative facets are very simple and are declared using @aspect annotations:

@Aspectpublic class Adivcemethod {
Then, when the slice is declared as a bean in the configuration file, Spring automatically recognizes and configures the AOP:

<bean id= "aspect" class= "... Adivcemethod "/>
Or the method of using meta annotations directly:

@Component @aspectpublic class Adivcemethod {
1.3. Declaration of entry Point

@AspectJ-style named Pointcuts are implemented using the @pointcut+ method under the Org.aspectj.lang.annotation package (the method must be a return void type).

          @Pointcut (value= "pointcut expression", ArgNames = "parameter Name list")          

Value:Specifies the pointcut expression;

argNames: Specifies a named Pointcut method parameter list parameter name, which can be separated by a "," parameter that will be passed to a parameter with the same name as the notification method, such as a pointcut expression "args (param)" The parameter type specified by the parameter with the same name as the named Pointcut method will match the parameter type.

pointcutname: pointcut name, which can be used to reference the pointcut expression.

    @Pointcut (value= "Execution (* cn.javass). *.sayadvisorbefore (..)) && args (param) ", argNames =" param ") public      void Beforepointcut (String param) {}  
Defines a pointcut with the name "Beforepointcut", which matches the first parameter type of the target method to the parameter type named "param" in the notification method implementation.

ii. Notice of declaration

@AspectJ-style declaration notifications also support 5 notification types:

2.1. Pre-Notification: Use the @before Note statement under the Org.aspectj.lang.annotation package;

    @Before (value = "Pointcut expression or named Pointcut", argNames = "argument list parameter name")  
Value:Specify pointcut expressions or named pointcuts;

ArgNames: synonymous with schema mode configuration.

Let's take a look at the following example:

1, define the interface and implementation, here we use the schema style when the definition;

2. Define FACETS:

3. Define the entry point:

4. Definition Notification:

2.2. Back notification: Use the @afterreturning Note statement under the Org.aspectj.lang.annotation package;

    @AfterReturning (      value= "pointcut expression or named Pointcut",      pointcut= "pointcut expression or named Pointcut",      argnames= "argument list parameter name",      returning= "return value corresponding to parameter name")  

Value: Specifies a pointcut expression or a named pointcut;

pointcut: also specifies a pointcut expression or named Pointcut, Pointcut has a high priority if specified to overwrite the Value property;

ArgNames: synonymous with schema mode configuration;

returning: synonymous with schema mode configuration.

2.3. Post-Exception notification: Use the @afterthrowing Note statement under the Org.aspectj.lang.annotation package;

@AfterThrowing (  value= "pointcut expression or named Pointcut",  pointcut= "pointcut expression or named Pointcut", argnames= "  argument list parameter name",  throwing= " Exception corresponding parameter name ")  

Value: Specifies a pointcut expression or a named pointcut;

pointcut: also specifies a pointcut expression or named Pointcut, Pointcut has a high priority if specified to overwrite the Value property;

ArgNames: synonymous with schema mode configuration;

throwing: synonymous with schema mode configuration.

Where the test code is almost the same as the schema mode, it is not demonstrated here, if necessary, refer to the Testannotationafterthrowingadvice test method in Aoptest.java.

2.4, after the final notice: the use of Org.aspectj.lang.annotation package under the @after Note statement;

    @After (      value= "pointcut expression or named Pointcut",      argnames= "argument list parameter name")  

Value: Specifies a pointcut expression or a named pointcut;

ArgNames: synonymous with schema mode configuration;

2.5, Surround Notice: Use the @around Note statement under the Org.aspectj.lang.annotation package;

    @Around (      value= "pointcut expression or named Pointcut",      argnames= "argument list parameter name")  

Value: Specifies a pointcut expression or a named pointcut;

ArgNames: synonymous with schema mode configuration;

2.6 Introduction

The introduction of the @AspectJ-style declaration uses the @declareparents declaration under the Org.aspectj.lang.annotation package in the slice:

    @DeclareParents (      value= "ASPECTJ syntax type expression",      Defaultimpl= introduces the default implementation class of the interface)      private Interface Interface;  

value: matches the ASPECTJ syntax type expression of the target object that needs to be introduced into the interface, and is synonymous with the types-matching attribute in the schema mode;

Private Interface Interface: Specifies the interface to be introduced;

Defaultimpl: Specifies the default implementation class that introduces the interface, and there is no way to define the synonym for the delegate-ref attribute in the schema mode;


iii. Examples of use

The entire project directory is as follows:


Remember to import the package: aopalliance-1.0.jar+aspectjweaver.jar+commons-logging-1.2.jar+spring

1. First create a new person's interface class:

Package com.mucfu.aspectj;/**  * Functional  Person Interface class * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.27*/public interface Person {public void eatbreakfast ();p ublic void Eatlunch ();p ublic void Eatsupper ();p ublic String drink (string name);}
2, to a baby's implementation class:

Package Com.mucfu.aspectj;import org.springframework.stereotype.component;/**  * Functional  Person Implementation class * Author Lin Bingwen (email Protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.27*/@Componentpublic class Babyperson implements person{ @Overridepublic void Eatbreakfast () {System.out.println ("Baby is eating Breakfast");} @Overridepublic void Eatlunch () {System.out.println ("Baby is eating lunch"); @Overridepublic void Eatsupper () {System.out.println ("Baby is eating dinner"); @Overridepublic string Drink (string name) {return "Baby is Drinking:" +name;}}

3, then is the function of bayby to eat a variety of enhancements

Package Com.mucfu.aspectj;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.After; Import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.springframework.stereotype.Component, @Component @aspectpublic class Adivcemethod {@Before ("Execution (* com.mucfu.aspectj.babyperson.* (..)) ") Match all methods of the Babyperson class, note that there is a space between * and com public void Beforeeat () {System.out.println ("-------------------here is the predecessor enhancement, Wash your hands first before you eat! --------------------");} @After ("Execution (* eatlunch (..))") Match all the Eatlunch methods under the project public void Aftereat () {System.out.println ("-------------------here is the post enhancement, after lunch to take a nap!" --------------------");} @Around ("Execution (* Com.mucfu.aspectj.BabyPerson.eatSupper ())")//Match the Eatlunch method of Babyperson under this project public Object Aroundeat (Proceedingjoinpoint pjp) throws Throwable {System.out.println ("-------------------here is surround enhancement, have a play before dinner! -------------------"), Object retVal = Pjp.proCeed (); System.out.println ("-------------------here is surround enhancement, after supper eat to sleep!"    -------------------"); return retVal;} @AfterReturning (returning= "rvt", pointcut= "Execution (* com.mucfu.aspectj.BabyPerson.drink (..))")    public void log (Object rvt) {System.out.println ("-------------------here is afterreturning enhanced-------------------");    System.out.println ("Get the drink that little baby is drinking" +rvt); System.out.println ("Record drink volume per day");}}
4, a new beans.xml, the contents are as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schem A/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframewor K.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframe Work.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "><!--designated automatic search The Lasso bean component, auto-Search Slice class--><context:component-scan base-package= "COM.MUCFU"/><!--start @aspectj support--><!-- Proxy-target-class default "False", change to "ture" using cglib dynamic Agent--<aop:aspectj-autoproxy proxy-target-class= "false"/> </beans>

5, the most later test

Package Com.mucfu.aspectj;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Test {public static void main (String [] args) {ApplicationContext context = new Classpathxmlapplicationcontext ("Beans.xml"); Person person= (person) context.getbean ("Babyperson");    Person.eatbreakfast ();    System.out.println ("===================================================");    Person.eatlunch ();    System.out.println ("===================================================");    Person.eatsupper ();    System.out.println ("===================================================");    Person.drink ("Cola");    System.out.println ("===================================================");}}

Output Result:


Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka


Summary and case of "Spring" AOP based on ASPECTJ annotations

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.