Spring Details (v)------AspectJ implementation of AOP

Source: Internet
Author: User
Tags throw exception throwable

In our previous blog, we brought up the concept of AOP and the implementation of AOP in a specific way. But why do we do this? And how does the pointcut expression come to be understood?

In this blog we will learn more about the introduction of the AspectJ framework.

1. What is AspectJ?

ASPECTJ is a tangent-oriented framework that extends the Java language. AspectJ defines the AOP syntax, or AspectJ is an AOP framework based on the Java language. Usually when we use Spring AOP, we import AspectJ related jar packages.

  

After spring2.0, Spring adds support for the AspectJ pointcut expression, Aspect1.5 new annotation feature, which can be defined directly in the class by JDK5 annotation technology, and the new version of the spring Framework also recommends using AspectJ to implement AOP. So, there is support for AspectJ in the core package Spring-aop-3.2.jar of Spring AOP.

2. Pointcut expression

In the previous blog, we configured the following in the spring configuration file:

<!--pointcut expression--><aop:pointcut expression= "Execution (* com.ys.aop.*.* (..))" id= "Mypointcut"/>

Then it means that the return value is arbitrary, the package name is any method name in any class name under COM.YS.AOP, and the parameter is arbitrary. So what does this mean?

First execution is a pointcut function defined by the AspectJ framework, which has the following grammatical form:

Execution (Modifiers-pattern? Ref-type-pattern Declaring-type-pattern? Name-pattern (Param-pattern) throws-pattern?)   class modifier           return value           method The exception that is                  thrown by the package method name                     method

The simple point is:

Syntax: Execution (modifier  Returns a value  package.) class. Method name (parameter) throws exception)

Specifically, let's take a look at the following mind mapping:

Note: What if a pointcut expression has multiple different directories? Available through | | To represent or to the relationship.

<aop:pointcut expression= "Execution (* com.ys.*service1.* (..)) | |                           Execution (* com.ys.*service2.* (..)) "id=" Mypointcut "/>

Any method that represents a class that matches the Com.ys package, ending with Service1 or ending with Service2.

  

AOP pointcut Expressions support Many forms of definition rules:

1. Execution: Execution of matching method (common)        Execution (public * * (..)) 2.within: Match a method in a package or a child package (learn) within (COM.YS.AOP). *) 3.this: Matches the method in the proxy object that implements the interface (understanding) This (Com.ys.aop.user.UserDAO) 4.target: Matches the method in the target object that implements the interface (understanding) Target ( Com.ys.aop.user.UserDAO) 5.args: Matching parameter format conforms to standard method (understanding) args (Int,int) 6.bean (ID)  all methods (understanding) beans (') for the specified bean (' Userserviceid ')

  

2. Aspect Notification type

The Aspect notification type, which defines the type name and method format. Types are as follows:

        Before: The pre-notification (application: various checks) executes before the method executes, if the notification throws an exception, the blocking method runs Afterreturning: The post-notification (apply: General data Processing) method returns after normal execution, if an exception is thrown in the method, The notification cannot be executed until the method executes, so the return value of the method can be obtained. Around: Surround notification (application: Very powerful, can do anything) before and after the method execution, you can prevent the execution of the method must manually execute the target method afterthrowing: Throw exception Notification (application: Wrapper exception information) method throws an exception after execution, if the method does not throw an exception, Cannot perform after: Final notification (application: cleanup site) execution after execution of the method, regardless of whether an exception occurred in the method

The most important thing here is the around, surround notification, which can replace any of the above notifications.

The meanings expressed in the program are as follows:

try{     //front: Before    //manual execution of target method    //post: afterretruning} catch () {    //Throw exception afterthrowing} finally{    //FINAL After

The corresponding jar packages are as follows:

  

We can view the source code:

  

3. Specific examples of AOP

  ①, creating interfaces

Package Com.ys.aop;public interface UserService {//Add userpublic void AddUser ();//delete userpublic void DeleteUser ();}

  ②, creating an implementation class

Package Com.ys.aop;public class Userserviceimpl implements userservice{@Overridepublic void AddUser () { System.out.println ("Add User");} @Overridepublic void DeleteUser () {System.out.println ("delete User");}}

③, creating slice classes (with various notifications)

Package Com.ys.aop;import Org.aspectj.lang.joinpoint;public class Myaspect {/** * Joinpoint can get some basic information about the target method * @param JOINP oint */public void Mybefore (Joinpoint joinpoint) {System.out.println ("Pre-Notification:" + joinpoint.getsignature (). GetName ());} public void myafterreturning (Joinpoint joinpoint,object ret) {System.out.println ("Post notification:" + joinpoint.getsignature (). GetName () + ",--" + ret);} public void Myafter () {System.out.println ("final Notice");}}

  ④, creating a spring profile Applicationcontext.xml

We first test the pre-notification, post-notification, final notification

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xsi:schemalocation=" Http://www.sprin Gframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd HTTP://WWW.SPR INGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd "><!--1, creating a target class-->& Lt;bean id= "UserService" class= "Com.ys.aop.UserServiceImpl" ></bean> <!--2, creating slice classes (notifications)---<bean id= " Myaspect "class=" Com.ys.aop.MyAspect "></bean><!--3, AOP programming 3.1 importing Namespaces 3.2 using <aop:config> Configure proxy-target-class= "true" declaration when using Cglib proxy if not declared, Spring automatically chooses Cglib proxy or JDK dynamic proxy <aop:pointcut> pointcut to get concrete methods from target objects <aop:advisor> special facets, only one notification and one pointcut ADVICE-REF notification reference pointcut-ref pointcut reference 3.3 pointcut expression Execution (* com.ys.aop.*.* (..)) Select method return value any package class name arbitrary method name arbitrary parameter arbitrary--><aop:config>< Aop:aspect ref= "Myaspect" ><!--pointcut expression--><aop:pointcut expression= "Execution (* com.ys.aop.*.* (..))" id= "Mypointcut"/><!--3.1 pre-notification <aop:before method= "pointcut=" "pointcut-ref=" "/>method: Notification, and method name Pointcut: Pointcut expression, which can only be used by the current notification. Pointcut-ref: pointcut Reference, you can share pointcuts with other notifications. Notification method format: public void Mybefore (Joinpoint joinpoint) {parameter 1:org.aspectj.lang.joinpoint is used to describe the connection point (target method), get the target method name, etc.-->< Aop:before method= "Mybefore" pointcut-ref= "Mypointcut"/><!--3.2 post notification, execute after target method, get return value <aop:after-returning Method= "" pointcut-ref= "" returning= ""/>returning notification method The name of the second parameter notifies the method format: public void myafterreturning (joinpoint Joinpoint,object ret) {parameter 1: Connection point description Parameter 2: Type Object, parameter name returning= "ret" Configuration--><aop:after-returning method= " Myafterreturning "pointcut-ref=" Mypointcut "returning=" ret "/><!--3.3 final notification--><aop:after method=" MyAfter "Pointcut-ref=" Mypointcut "/></aop:aspect></aop:config></beans>

  ⑤, testing

@Testpublic void Testaop () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml") ; UserService Useservice = (userservice) context.getbean ("UserService"); Useservice.adduser ();}

  Console printing:

  

Note that the return value of the post notification is NULL because our target method AddUser () has no return value. If there is a return value, this is the return value of AddUser ().

  

4. Test exception notification

The target interface remains the same, and we manually introduce the exception to the target class:

public void AddUser () {int i = 1/0;//Obviously this will throw a divisor that cannot be 0system.out.println ("Add User");}

Then configure the slice: Myaspect.java

public void myafterthrowing (Joinpoint joinpoint,throwable e) {System.out.println ("Throw exception Notification:" + e.getmessage ());}

Next, configure the following in Applicationcontext.xml:

<!--3.4 Throws an exception <aop:after-throwing method= "" pointcut-ref= "" throwing= ""/>throwing: Notification method's second parameter name notification method format: public void Myafterthrowing (Joinpoint joinpoint,throwable e) {parameter 1: Connection point Description Object Parameter 2: Get exception information, type Throwable, parameter name is configured by throwing= "E"- <aop:after-throwing method= "myafterthrowing" pointcut-ref= "Mypointcut" throwing= "E"/>

Test:

@Testpublic void Testaop () {String str = "Com/ys/execption/applicationcontext.xml"; ApplicationContext context = new Classpathxmlapplicationcontext (str); UserService Useservice = (userservice) context.getbean ("UserService"); Useservice.adduser ();}

Console printing:

  

5. Test Surround Notification

The target interface and the target class remain unchanged, and the slice Myaspect is modified as follows:

public class Myaspect {public Object myaround (Proceedingjoinpoint joinpoint) throws Throwable{system.out.println ("Pre-notification ");//manual execution of the target method object obj = Joinpoint.proceed (); SYSTEM.OUT.PRINTLN ("post notification"); return obj;}}

The Applicationcontext.xml configuration is as follows:

<!--surround notification <aop:around method= "" pointcut-ref= ""/> Notification method format: public Object myaround (Proceedingjoinpoint joinpoint ) throws throwable{return value type: Object method Name: Arbitrary parameter: Org.aspectj.lang.ProceedingJoinPoint throws Exception execution target method: Object obj = Joinpoint.proceed ();--><aop:around method= "Myaround" pointcut-ref= "Mypointcut"/>

Test:

@Testpublic void Testaop () {String str = "Com/ys/around/applicationcontext.xml"; ApplicationContext context = new Classpathxmlapplicationcontext (str); UserService Useservice = (userservice) context.getbean ("UserService"); Useservice.adduser ();}

Printing results:

  

So far, we have explained the configuration of spring AOP in the way of XML configuration. The next chapter will be implemented in the form of annotations.

Spring Details (v)------AspectJ implementation of AOP

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.