Introduction to Spring AOP

Source: Internet
Author: User
Tags testng

Introduction

AOP is the product of the development of software development to a certain stage, the emergence of AOP is not to replace OOP, only as a useful complement to OOP, in the following example, this concept will be verified. AOP applications are limited and generally apply to applications with crosscutting logic, such as performance monitoring, access control, transaction management, and logging. AOP is difficult to use in common application development, but AOP is one of the highlights of spring and it is necessary to look at it.


An AOP as well as terminology

AOP is the abbreviation of Aspect oriented programing, which is translated into plane-oriented programming. AOP wants to extract the same code that is scattered in the business logic functions into a separate module. As an example:

Class a{    public void run ()     {             dosomething ();             doathings ();             dootherthing ();     }}class b{    public void run ( )     {            dosomething ( );             dobthings ();             dootherthing ();    }}class c{     public void run ()     {             dosomething ();             docthings();             dootherthing ();             domorethings ();     }}

For example, the Run method in the three classes above has dosomething and dootherthing code, and AOP is to extract the code. We know that extracting code is easy, but how to integrate these independent logic code into the business class to complete the same business operations as the original, this is the problem of AOP to solve.

Terms

Joinpoint connection point: A specific location of the program execution, such as before the class is initialized, after the class is initialized, after the method executes, and so on, spring only supports the connection point of the method, that is, the method executes before the method throws an exception.

Pointcut tangency: Each class has multiple connection points, such as a class with two methods, both of which are connection points that can locate one or more connection points in a connection point.

Advice enhancement: The Enhancement is a program code that weaves into the target class connection point, that is, when the program arrives at an execution point and executes the corresponding piece of code, spring provides the advice with an access point orientation, such as Beforeadvice, Aftereturningadvice,throwsadvice and so on. Only binding pointcuts and notifications can determine a specific connection point and execute the corresponding code.

Target object: The class in which the code is embedded.

Introductiony Referral: You can add properties and methods to a class.

Weaving weaving: AOP is like a loom that embeds enhanced code into the corresponding class. AOP has three ways of weaving:

    • Compile-time weaving: This requires a special Java compiler

    • Class loading time: Requires special class loaders

    • Dynamic agent weaving: weaving in a way that generates proxy objects for target objects at run time

Spring uses dynamic agent weaving, aspectj with compile-time weaving and class loading weaving.

Proxy: Once a class is woven into AOP, it produces a proxy object that incorporates the original class code and the enhanced code.

Aspect Facets: composed of tangency points and enhancements , he includes definitions of connection point definitions and crosscutting logic code, and SPRINGAOP is the framework responsible for implementing facets.


Two AdviceEnhanced

Spring uses an enhanced class to define crosscutting logic, and the enhanced class also includes information on which point in the method to add code.

Enhanced Type

    • Pre-enhancement: Enforcing enhancements prior to method execution

    • Post enhancement: Enforcing enhancements after method return

    • Exception throwing enhancements: Enforcing enhancements after a target method throws an exception

    • Surround enhancement: Enforcing enhancements before and after a method is executed

    • Introduction enhancement: Adding new methods and properties to the target class

Next, I'll explain the top four enhancements in a simple example

dog.java//defines the interface of the dog package test.aop;/** * created by gavin on 15-7-18.  */public interface dog {    public void shout (String name);     public void sleep (string name);} chinadog.java//Design Chinese Pastoral dog package test.aop;/** * created by gavin on 15-7-18.  */public class ChinaDog implements Dog {     @Override      public void shout (String name)  {         system.out.println ("Chinese Pastoral Dog" +name+ "  called");     }    @ Override    public void sleep (String name)  {         system.out.println ("Chinese Pastoral Dog" +name+ "  Asleep");    }     public void error ()  throws excEption {        throw new exception ("shout  Exception ");     }}//beforeadvice.java//pre-enhancement class package test.aop;import  org.springframework.aop.methodbeforeadvice;import java.lang.reflect.method;/** * created  by gavin on 15-7-18. */public class beforeadvice implements  methodbeforeadvice {     @Override     public void before (Method method, object[] objects, object o)  throws Throwable {         String name =  (String) objects[0];     //parameter Get         system.out.println ("Chinese Pastoral Dog" +name+ "  Front enhancement");     }}//afterreturnadvice.java//post-Enhancement class package test.aop;import  Org.springframework.aop.afterreturningadvice;import java.lang.Reflect. method;/** * created by gavin on 15-7-18. */public class  afterreturnadvice implements afterreturningadvice {     @Override      public void afterreturning (object o, method method, object[]  OBJECTS, OBJECT O1)  throws Throwable {         String name =  (String) objects[0];         System.out.println ("Chinese Pastoral Dog" +name+ "  post Enhancement");     }}//surroundadvice.java//Surround Enhancement class Package  test.aop;import org.aopalliance.intercept.MethodInterceptor;import  Org.aopalliance.intercept.methodinvocation;/** * created by gavin on 15-7-18.  */public class SurroundAdvice implements MethodInterceptor {      @Override     public object&Nbsp;invoke (methodinvocation methodinvocation)  throws Throwable {         object[] objects = methodinvocation.getarguments ();         String name =  (String) objects[0];         SYSTEM.OUT.PRINTLN ("Surround enhancement----ago" +name);         object  object = methodinvocation.proceed ();     //the original function is performed here          SYSTEM.OUT.PRINTLN ("Surround enhancement----after" +name);         return object;    }}//throwadvice.java//exception throw Enhancement class Package test.aop;import  org.springframework.aop.ThrowsAdvice;import java.lang.reflect.Method;/** * Created  by gavin on 15-7-18. */public class throwadvice implements  throwsadvice {     @Override     public void afterthrowing (method method,object[]  ARGS, OBJECT OBJ ,EXCEPTION EX) throws throwable    {         system.out.println ("------------------------");         SYSTEM.OUT.PRINTLN ("------Exception throw enhancement");         SYSTEM.OUT.PRINTLN ("------method " +method.getname ());         SYSTEM.OUT.PRINTLN ("------exception " +ex.getmessage ());         System.out.println ("------------------------");     }}//AOPTEST.JAVA//AOP test class package  test.aop;import org.aopalliance.aop.advice;import org.springframework.aop.framework.proxyfactory; import org.springframework.context.applicationcontext;import  Org.springframework.context.support.filesystemxmlapplicationcontext;import org.testng.annotations.beforetest;import org.testng.annotations.test;/** * created  by gavin on 15-7-18. */public class AopTest {     private dog dog;    private advice advice;     private proxyfactory pf;     @BeforeTest     public void  init ()     {        dog = new  Chinadog ();         pf = new proxyfactory ();         pf.settarget (dog);    }     @Test     public void beforeadvice ()     {         advice = new beforeadvice ();         pf.addadvice (ADVice);        dog dog =  (Dog) pf.getproxy ();         dog.shout ("Jim");         dog.sleep ("Tom");    }     @Test     public void  Afterreturndvice ()     {        advice =  New afterreturnadvice ();         pf.addadvice (advice);         Dog dog =  (Dog) pf.getproxy ();         dog.shout ("Jim");         dog.sleep ("Tom");     }     @Test     public void arroundadvice ()     {        surroundadvice advice =  new surrouNdadvice ();         pf.addadvice (advice);         Dog dog =  (Dog) pf.getproxy ();         Dog.shout ("Jim");         dog.sleep ("Tom");     }      @Test     public void throwadvice ()      {        advice = new throwadvice ();         pf.addadvice (advice);         chinadog dog =  (Chinadog) pf.getproxy ();         try  {            dog.error ();         } catch  (exception e)  {             e.printstacktrace ();         }    }} 

Four kinds of enhancement methods were tested, and the following results were obtained:

Front-mounted enhancements

Post Enhancement

Surround enhancement

Exception throw Enhancement

Three Create facets

After reading the above code, we may notice that the enhancement class is woven into all the methods of the target class, that is, the shout and sleep methods are enhanced. You need to use a tangent point to locate it.

Spring describes the pointcut through the Org.springframework.aop.Pointcut interface, which locates to a specific class through the classfilter of the interface and navigates to a specific method through Methodmatcher.

Matching facets with static regular expression methods

Add the following XML statement to the Applicationcontext.xml:

<!--aop--><!--  proxy object  --><bean class= "Test.aop.ChinaDog"  id= "Chinadog"/> <!--  Pre-notification  --><bean class= "Test.aop.BeforeAdvice"  id= "Beforeadvice"/><!--   Defining facets  --><bean id= "Beforeadvicefilter"  class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor ">       < Property name= "Advice"  ref= "Beforeadvice"/>       <property  name= "Patterns" >               <list>                      <value>s.*</value>               </list>       </property> </bean><!--  Proxy Object  --><bean class= "Org.springframework.aop.framework.ProxyFactoryBean"  id= "Proxyfactorybean" >        <!--  Set Proxy interface collection  -->       <property  name= "Proxyinterfaces" >               <list>                      <!--interface to write full-->                      <value>test.aop.dog</value >              </list>        </property>       <!--   -->       <property name= "InterceptorNames" > of enhanced Weaving Agent object               <list>                      <value> beforeadvicefilter</value>               </list>       </property>        <!--  Configure proxied objects  -->       <property name= " Target " ref=" Chinadog "/></bean>

Call Applicationcontext.xml in Aoptest.java:

public static void Main (string[] args) {//propertyconfigurator.configure ("web/web-inf/log4j.properties");    ApplicationContext ac = new Filesystemxmlapplicationcontext ("Web/web-inf/applicationcontext.xml");    Dog dog = (dog) ac.getbean ("Proxyfactorybean");    Dog.shout ("Jim"); Dog.sleep ("Tom");

Result of the previous enhancement.


Four-based @aspectj configuration facets

In the third section we use the pointcut and advice interfaces to describe pointcuts and enhancements, and use the advisor to integrate descriptive facets, @AspectJ to describe tangency and enhancement using annotations, and to describe exactly the same content, except in a different way.

We first define a slice with @aspectj:

Package Test.aop;import Org.aspectj.lang.annotation.aspect;import org.aspectj.lang.annotation.before;/** * Created By Gavin on 15-7-18. */@Aspectpublic class Preaspect {@Before ("Execution (* shout (..))")    means the return value arbitrary parameter any public void Beforeshout () {System.out.println ("Ready to call"); }}

Set in Applicationcontext.xml:

<!--Aop--><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.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.1.xsd "><!-- Drive--><aop:aspectj-autoproxy/><bean class= "Test.aop.PreAspect"/> Based on @aspectj facets

To test in Aoptest.java, the code is as follows:

public static void Main (string[] args) {//propertyconfigurator.configure ("web/web-inf/log4j.properties");    ApplicationContext ac = new Filesystemxmlapplicationcontext ("Web/web-inf/applicationcontext.xml");    Dog dog = (dog) ac.getbean ("Chinadog");    Notice here Dog.shout ("Jim"); Dog.sleep ("Tom");

The result is:

The Beforeshout method is called only before the Shout method.


Summarize

AOP is a useful complement to OOP, and he provides a new perspective for program development that can extract repetitive crosscutting logic into a unified module. Only through the vertical abstraction of OOP and the horizontal extraction of AOP can a program really solve repetitive code problems.

Spring uses JDK dynamic agent and Cglib Dynamic Agent technology to weave enhancements during runtime. So the user does not have to equip a special compiler or class loader. To use the JDK dynamic proxy, the target object must implement the interface, and the cglib does not impose restrictions on the target class.

The JDK creates a proxy object that is more efficient than cglib, and Cglib creates a proxy object that runs more efficiently than the JDK.

Introduction to 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.