Teach you how to use spring AOP

Source: Internet
Author: User
Tags throwable

Using spring for a long time, always wanted to write something AOP, but has not been idle, until now the project is a little on the right track, just hurriedly write. Needless to say, start with an introduction to AOP, and then introduce the principles of AOP (JDK dynamic code and Cglib dynamic code knowledge). Note: This section is suitable for children's shoes that have not touched the spring AOP, if it is an AOP veteran, please bypass directly, do not say hello ^ ^

Please respect the author's labor results, reproduced please indicate the original link:

Https://www.cnblogs.com/jpcflyer/p/9339104.html

First, the Environment preparation

1. Download the Springframework related jar package in the spring website (address at the end of this article), and the jar package will contain aop/aspects/context/beans/core and other related jars.

2. On the ASPECTJ website (AOP dependency package, address at the end of this article) download Aspectj.jar, the latest stable version is 1.9.1.

3. In eclipse, create a new Java project, create a new Lib directory under the root directory, and copy all the jar packages downloaded in step 1th to the Lib directory.

4. Extract the Aspectj.jar from the 2nd step and copy the extracted Aspectjrt.jar and Aspectjweaver.jar two jar packages to the Lib directory.

5. Project Right--build path-libraries-add jars, then select all the jar packages in Lib and click OK.

6. In the project root directory new configuration file Applicationcontext.xml, the file content is temporarily empty, to this environment ready to complete.

Second, code example

Kids who know about AOP know how many ways to use AOP, and here's how to use configuration files to reduce the injection of code and be more concise.

1. New Slice Class

 Packagetest;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.aspectj.lang.ProceedingJoinPoint; Public classAspectadvice {/*** PRE-notification * *@paramJP*/     Public voidDobefore (joinpoint JP) {System.out.println ("=========== into before advice============ \ n"); System.out.print ("Ready on" + Jp.gettarget (). GetClass () + "object with"); System.out.print (Jp.getsignature (). GetName ()+ "Method for"); System.out.print (Jp.getargs () [0] + "' To delete! \ n "); System.out.println ("To enter the Pointcut method, \ n"); }    /*** POST Notification * *@paramJP * Connection point *@paramresult * return value*/     Public voidDoafter (joinpoint JP, String result) {System.out.println ("========== into after advice=========== \ n"); System.out.println ("The Pointcut method is done \ nthe"); System.out.print (Jp.getargs () [0] + "in"); System.out.print (Jp.gettarget (). GetClass ()+ "Object is"); System.out.print (Jp.getsignature (). GetName ()+ "Method Removed"); System.out.print ("Only left:" + result + "\ n"); }    /*** Surround Notice * *@paramPJP * Connection point*/     Public voidDoaround (Proceedingjoinpoint PJP)throwsthrowable {System.out.println ("=========== into the around wrapping Method! =========== \ n "); //action to execute before calling the target methodSystem.out.println ("Before calling Method: Execute!") \ n "); //parameters of the calling methodobject[] args =Pjp.getargs (); //method name to invokeString method =pjp.getsignature (). GetName (); //get target ObjectObject target =Pjp.gettarget (); //execution of the return value of the method: calling the proceed () method triggers the Pointcut method executionObject result =pjp.proceed (); System.out.println ("Output:" + args[0] + ";" + method + ";" + target + ";" + result + "\ n"); System.out.println ("Call method End: Execute after!" \ n "); }    /*** Exception Notification * *@paramJP *@parame*/     Public voidDothrow (joinpoint JP, Throwable e) {System.out.println ("Delete error."); }}
View Code

2. New Business Class

 Packagetest; Public classaspectbusiness { Publicstring Delete (String obj) {System.out.println ("========== call Pointcut:" + obj + "said: You dare to delete me!" ===========\n "); returnobj + ": Aim ~"; }     Publicstring Add (String obj) {System.out.println ("================ This method cannot be cut ... ============== \ n "); returnobj + ": Aim ~ Hehe! "; }     Publicstring Modify (String obj) {System.out.println ("================= This also set join cut bar ====================\n"); returnobj + ": Aim and AIM! "; }}
View Code

3. In Applicationcontext.xml, add the following:

<?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:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop.xsd "><!--Bean Definitions here--<!--declaring a business class--<bean id= "Aspectbusiness"class= "Test. Aspectbusiness "/> <!--notice class--<bean id=" Aspectadvice "class= "Test. Aspectadvice "/> <aop:config> <aop:aspect id=" Businessaspect "ref=" Aspectadvice "> < !--configuration Specifies the object to cut in-<aop:pointcut id= "point_cut" expression= "Execution (* test.*.* (..))"/> &L t;! --Match only the Add method as a pointcut<aop:pointcut id= "Except_add" expression= "Execution (* test.*.add (..))"/>-<!--pre-notification  --<aop:before method= "Dobefore" pointcut-ref= "Point_cut"/> <!--post notification returning specify return parameters --<aop:after-returning method= "Doafter"pointcut-ref= "Point_cut" returning= "result"/> <aop:around method= "Doaround" pointcut-ref= "Point_cut"/> <aop:after-throwing method= "Dothrow" pointcut-ref= "Point_cut" throwing= "E"/> </aop:aspect> < /aop:config></beans>
View Code

4. New Test class

 Packagetest;Importjava.util.ArrayList;Importjava.util.Collection;Importjava.util.LinkedList;Importjava.util.List;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classStringtest { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Aspectbusiness Business= (aspectbusiness) context.getbean ("Aspectbusiness"); Business.delete (Cat); }}
View Code

Iii. Results of operation

The results of the operation are as follows:

=========== into before advice============' cat '=========== into around surround Method! =========== before calling the method: Execute! ========== call Pointcut: Cat says: You dare to delete me! =========== output: cat; delete; [email protected]; Cat: Aim ~ Call Method End: Then execute! ========== enters after advice=========== the Pointcut method executes the Cat in class test. The Delete method on the Aspectbusiness object has been deleted leaving only:null

So the example of AOP, even if completed, this article does not introduce the aspect, notice, pointcuts and other related concepts, these concepts in Baidu is a handy, if you do not understand, you can own Baidu. This article first to write here, followed by the introduction of the relevant principles of AOP.

Resources:

1. Spring Official website: https://spring.io/

2. Spring4.0 Official website: https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-local/org/ Springframework/spring/5.0.0.release

3. ASPECTJ latest stable version official website: http://www.eclipse.org/aspectj/downloads.php#stable_release

Teach you how to use spring 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.