ASPECTJ Quick Start code example Before,after,around

Source: Internet
Author: User

This article does not intend to explain the relevant professional terminology and concepts of AOP, only a few code examples are used to demonstrate the basic use of ASPECTJ (implemented for AOP), and the ASPECTJ used is the current version.


1. Build the Environment

This article uses MAVEN to build the project using the Aspectj-maven-plugin plugin to compile the *.aj file to the. class.

MAVEN's specific configuration:

<plugin><groupid>org.codehaus.mojo</groupid><artifactid>aspectj-maven-plugin</ artifactid><version>1.7</version><configuration><compliancelevel>1.6</ Compliancelevel></configuration></plugin>

Can be configured under the configuration node above

<aspectDirectory></aspectDirectory>

The default is Src/main/aspect, which can be set as needed.

Configuring the ASPECTJ Runtime Environment dependent jar

<dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId>< Version>1.8.2</version></dependency>


2. Create a generic Java Class (Simple.java) to prepare for the next use of ASPECTJ to implant the appropriate functionality

Package Com.rft.fdsi.server.aop;public class Simple {static {System.out.println ("[src] static init");} Public simple () {System.out.println ("[src] construct");} public string Welcome (string name) {System.out.println ("[src]===========start==========="); System.out.println ("[src] Welcome method Execute"); System.out.println ("[src] Welcome method Execute"); System.out.println ("[src]===========end===========");//throw New RuntimeException ("Runtime exception"); return " Welcome "+ Name;} public static void Main (string[] args) {Simple simple = new simple (); String greeting = simple.welcome ("Jack"); System.out.println (greeting);}}

3. Create a static code block initialization for the simple class, construct the method execution, and invoke the Aspect Class (Simpleaspect.aj) of the method call for the implant function.

 

package com.rft.fdsi.server.aop;public aspect simpleaspect {public pointcut  Staticinit ()  : staticinitialization (com.rft.fdsi.server.aop.Simple); before ()  : staticinit ( )  {system.out.println ("[Before]" + thisjoinpointstaticpart.getsignature (). GetName ());} After ()  returning ()  : staticinit ()  {system.out.println ("[After returning]" +  Thisjoinpointstaticpart.getsignature (). GetName ());} Before ()  : call (Public com.rft.fdsi.server.aop.*.new ())  {system.out.println ("[Before]"  + thisjoinpoint.getsignature (). GetName ());} After ()  : call (Public com.rft.fdsi.server.aop.*.new ())  {system.out.println (' [after] '   + thisjoinpoint.getsignature (). GetName ());} Public pointcut welcomemethod (String name)  : call (public string  Com.rft.fdsi.server. *.welcome (String))  && args (name); before (String name):  welcomemethoD (name) {System.out.println ("[Before]" + thisjoinpoint.gettarget (). GetClass (). Getcanonicalname ()  +   "." + thisjoinpoint.getsignature (). GetName () +  " args_name="  + name); After (string name)  returning (string retval)  : welcomemethod (name)  { System.out.println ("[After returning]" + thisjoinpoint.gettarget (). GetClass (). Getcanonicalname ()  +  "." + thisjoinpoint.getsignature (). GetName ()  +  " args_name="  + name+  "  Return_value = " + retval);} After (string name)  : welcomemethod (name) {System.out.println ("[After]" +  Thisjoinpoint.gettarget (). GetClass (). Getcanonicalname ()  +  "." + thisjoinpoint.getsignature (). GetName () +  " args_name="  + name); After (string name)  throwing (java.lang.exception e)  : welcomemethod (name)  { System.out.println ("[After throwing]" + thisjoinpoint.gettarget(). GetClass (). Getcanonicalname ()  +  "." + thisjoinpoint.getsignature (). GetName ()  +  " throwing=" + e.getmessage ());}

The two pointcuts (Pointcut) shown above are: Staticinit () (The connection point of the pointcut is a static code block of the Simple Class), Welcomemethod (name) (The connection point of the pointcut is the Welcomemethod method of the Simple object); implicitly, the same pointcut is declared in the forward notification and the post-notification, and the connection of the pointcut is a simple construction method.

There are four types of notification types in the ASPECTJ built-in 5: Before (notification before connection point execution) after returning (notification after the connection point is complete), after throwing (notification after an exception occurs in connection point execution), after ( Notification after the connection point is complete, whether normal or abnormal. The other is the around (surround notification, which is notified after execution is completed before the connection point is executed).


Using Aspectj-maven-pugin to compile the Simpleaspect.aj file, execute the command: MVN aspectj:compile.


4. Test results

public static void Main (string[] args) {Simple simple = new simple (); String greeting = simple.welcome ("Jack"); System.out.println (greeting);}


If there is no aspject implant, the result above should be a simple input with "Welcome Jack", and now the results are as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6C/08/wKioL1U-L_KgK6c8AAK9oEFoDh0449.jpg "title=" Aspectj011.png "alt=" Wkiol1u-l_kgk6c8aak9oefodh0449.jpg "/>

After the throwing notification is not executed, remove the exception from the Welcome method in the simple class and comment out the return value, execute the test, and you will see that after throwing executes the notification after the connection point welcome performs the send exception.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6C/0D/wKiom1U-LzzS0Jb7AAMYJ5Vyaac737.jpg "title=" Aspectj022.png "alt=" Wkiom1u-lzzs0jb7aamyj5vyaac737.jpg "/>


5. Add around notifications in the Simpleaspect.aj aspect class, you also need to comment out the after and before notifications on the Welcomemethod pointcut expression, because you specify before,after at the same time, Around will have no hair to determine the order in which they are executed, and there is no need for before,after notification after the around notification is specified, around notification can achieve the effect of both notifications.


String around (string name): Welcomemethod (name) {System.out.println ("[around]========start========="); System.out.println ("[Around]" + thisjoinpoint.gettarget (). GetClass (). Getcanonicalname () + "." + thisjoinpoint.getsignature (). GetName () + "args_name=" + name); String retval = proceed (name); System.out.println ("[Around]" + thisjoinpoint.gettarget (). GetClass (). Getcanonicalname () + "." + thisjoinpoint.getsignature (). GetName () + "args_name=" + name+ "return_value=" + retval); System.out.println ("[around] Modify return value append '!!! ' =" + (retval = retval + "!!!")); System.out.println ("[around]========end========="); return retval;}


After performing the test, you can see that the around notification is executed at the connection point welcome method, which prints the output before the connection point is executed, obtains the return value after the connection point execution is completed, and returns after it has been modified. Around notifications are most powerful in the V notification type, and the actual application is selected according to the function to be implanted.


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6C/08/wKioL1U-ML7wX0ksAAM76I7FzXg085.jpg "title=" Aspectj033.png "alt=" Wkiol1u-ml7wx0ksaam76i7fzxg085.jpg "/>


To this end of the example, more information about ASPJECTJ See official website: http://www.eclipse.org/aspectj/docs.php


This article is from the "Red Horse Red" blog, please be sure to keep this source http://aiilive.blog.51cto.com/1925756/1639440

ASPECTJ Quick Start code example Before,after,around

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.