Spring AOP Understanding

Source: Internet
Author: User
Tags throwable

The core ideas of spring are IOC and AOP. Recently, learning about AOP has made a further understanding of the study of facets.

Spring uses proxy classes to wrap facets and weave them into spring-managed beans. In other words, the proxy class is disguised as the target class, it intercepts the call to the method in the target class, so that the caller calls the target class first to call the Masquerade class, the masked class first executes the slice, and then forwards the call to the real target bean. This allows for minimal intrusion into the business code. The coupling degree between the parts of business logic is reduced, and the reusability of the program is improved. In spring, logging, performance statistics, security control, transaction processing, and so on are all managed through AOP.

There are two ways to implement a masquerade class: 1. implement the same interface as the target class. In this brotherly mode,Spring uses the JDK's Java.lang.reflect.Proxy class, which allows spring to dynamically generate a new class to implement the necessary interfaces, weave notifications, and forward any calls to those interfaces to the target class.

2. generate subclass calls, using subclasses as camouflage classes. In this parent-child mode,Spring uses the Cglib library to generate a subclass of the target class, and when the subclass is created, spring weaves the notification and delegates the call to the subclass to the target class.

In contrast, the sibling mode is better, can be more loosely coupled, especially in today's shouting interface-oriented programming situation, the parent-child mode is only when the interface is not implemented, can also weave notification, should be treated as an exception.

Let's look at a small application of AOP. The purpose is to perform related operations through AOP before and after the Addstudent method executes.

Configure ASPECTJ in the context.

<Aop:aspectj-autoproxy/>Define facets, tangent points. Annotations can also be used to implement tangent and tangent identification of facets.<Aop:config>        <Aop:aspectID= "Studentserviceaspect"ref= "Studentserviceaspect">            <Aop:pointcutID= "Businessservice"expression= "Execution (* com.lufax.test.commen.studentservice.*.* (..))"/>            <Aop:beforeMethod= "Dobefore"Pointcut-ref= "Businessservice"/>            <Aop:afterMethod= "Doafter"Pointcut-ref= "Businessservice"/>            <Aop:aroundMethod= "Doaround"Pointcut-ref= "Businessservice"/>        </Aop:aspect>    </Aop:config>

The following defines the Studentservice interface.

 Public Interface Studentservice {    publicvoid  addstudent (String name);}

The implementation class for Studentservice is as follows.

 Public class Implements Studentservice {    publicvoid  addstudent (String name) {        System.out.println ("----is adding" + name+ "----");}    }

The above interfaces and implementations are normal business logic. Write a tangent below.

 Public classStudentserviceaspect {//Run before business code execution Public voidDobefore () {System.out.println ("Class Name:"); System.out.println ("Dobefore: Start adding students"); }
Run after the business code executes Public voidDoafter (joinpoint JP) {System.out.println ("Doafter: Add Complete");
You can use the Joinpoint class to print the log. Record the class and method names and parameters under the tangency point so that subsequent quick location problems are located. System.out.println ("[Class name +" +jp.gettarget (). GetClass (). GetName () + "]," + "[Method Name: +jp.getsignature (). GetName () +"], "+ "[Parameter:" +jp.getargs () [0]+ "]"); }
Surround notification, retval is the return value. This is null PublicObject Doaround (Proceedingjoinpoint PJP)throwsthrowable{System.out.println ("Doaround: Before joining"); Object RetVal=pjp.proceed (); System.out.println (RetVal); System.out.println ("Doaround: After joining"); returnRetVal; }}

implemented through annotations.

@Aspect Public classStudentserviceaspect {@Before (value= "Execution (* com.lufax.test.commen.studentservice.*.addstudent (..)) ")     Public voidDobefore () {System.out.println ("Class Name:"); System.out.println ("Dobefore: Start adding students"); } @After (Value= "Execution (* com.lufax.test.commen.studentservice.*.addstudent (..))")     Public voidDoafter (joinpoint JP) {System.out.println ("Doafter: Add Complete"); System.out.println ("[Class name +" +jp.gettarget (). GetClass (). GetName () + "]," + "[Method Name: +jp.getsignature (). GetName () +"], "+ "[Parameter:" +jp.getargs () [0]+ "]"); } @Around (Value= "Execution (* com.lufax.test.commen.studentservice.*.addstudent (..))")     PublicObject Doaround (Proceedingjoinpoint PJP)throwsthrowable{System.out.println ("Doaround: Before joining"); Object RetVal=pjp.proceed ();        System.out.println (RetVal); System.out.println ("Doaround: After joining"); returnRetVal; }}

Finally write the test class.

@Test      Public void Test_aopaspectj () {        new classpathxmlapplicationcontext ("Applicationcontext.xml", " Datasource.xml ");         = (Studentservice) applicationcontext.getbean ("Studentservice");        Studentservice.addstudent ("Zhang San");    }

The results of the operation are as follows:

class Name: Dobefore: Start adding student Doaround: Before joining ----adding Zhang San----doafter: Add complete [class name +  com.lufax.test.commen.studentservice.studentserviceimp],[method Name: addstudent],[parameter: Zhang San]nullDoaround : After joining

Spring AOP Understanding

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.