Using the spring approach to implement AOP programming

Source: Internet
Author: User

1: What is AOP?

Aspect oriented programming programming for facets
In the software industry, AOP is the abbreviation for Aspect oriented programming, which means: face-cutting programming, through the pre-compilation method and runtime dynamic agent to implement the unified maintenance of the program functions of a technology. AOP is a continuation of OOP, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

Object-oriented programming considers the structure of a program from a "static perspective", while aspect-oriented programming considers the program's running process from a "dynamic perspective."
The underlying AOP is implemented using the "Dynamic proxy" pattern. Two kinds of proxies are used: JDK dynamic agent and Cglib dynamic agent.

2:

Basic terms (some nouns):
(1) facets (Aspect)
Facets refer to [* Cross business logic *]. Transaction processing and log processing can be understood as facets. Commonly used facets have notification (Advice) and advisor (advisor). is actually an enhancement to the main business logic.

(2) weave in (Weaving)
Weaving refers to the process of inserting slice code into a target object. The agent's Invoke method completes the work that can be called weaving.

(3) connection point (Joinpoint)
A connection point refers to a method that can be woven into a plane. Usually the method of the business interface is the connection point

(4) entry point (PointCut)
The method by which the tangent point refers to the specific weaving
Note: Methods that are marked as final cannot be used as connection points and pointcuts. Because the final is cannot be modified, cannot be enhanced.

(5) destination Object (target)
The target object refers to the object that will be enhanced. That is, the object of the class that contains the primary business logic.

(6) notice (Advice)
Notifications are an implementation of facets that can be done with simple weaving functions. The notification defines the point in time at which the enhanced code is cut into the target code, whether the target method executes before execution, execution, and so on. The pointcut defines the cut-in position and notifies the definition of when to cut in.

(7) Advisor (advisor)
A consultant is another implementation of facets that can weave a notification into a target object in a more complex way, and is an assembler that wraps notifications into more complex facets.

3: Configure front, rear, surround, exception notification enhancements

Define interfaces:

 Package Methodbefore;  Public Interface Isomeservice {publicvoid  Dotran ();  Public void Dolog ();}

To define an implementation class:

 package   Methodbefore;  public  class  Someserviceimpl implements   Isomeservice {@ Override  public  void   Dotran () { //  TODO Auto-ge    nerated method Stub  System.out.println ("Transaction start"  public  void   Dolog () { //  TODO Auto-ge    nerated method Stub  System.out.println ("Log Start" 

To define a proxy class:

 PackageMethodbefore;ImportJava.lang.reflect.Method;Importorg.aopalliance.intercept.MethodInvocation;ImportOrg.springframework.aop.MethodBeforeAdvice;//Methodbeforeadvice front-facing interface//Afterreturningadvice Rear-facing interface//Methodinterceptor Surround Interface Public classMethodbeforeadviceimplImplementsMethodbeforeadvice//Afterreturningadvice Methodinterceptor{    //methods overridden in the Methodbeforeadvice interface@Override Public voidbefore (Method arg0, object[] arg1, Object arg2)throwsthrowable {System.out.println ("==before"); //System.out.println ("==after");    }        /*@Override * Methods overridden in the Afterreturningadvice interface public void afterreturning (Object arg0, Method Arg1, object[] arg2,            Object Arg3) throws Throwable {System.out.println ("===after====="); }*/        /*@Override * Overridden method in Methodinterceptor interface public Object invoke (Methodinvocation arg0) throws Throwable {Sys        Tem.out.println ("after");        Arg0.proceed ();        System.out.println ("before");    return null; }*/}

Configuration file:

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >   <BeanID= "Impl"class= "Mythrowsexception.someserviceimpl"></Bean>   <BeanID= "Before"class= "mythrowsexception.methodbeforeadviceimpl"></Bean>   <BeanID= "Beanfactory"class= "Org.springframework.aop.framework.ProxyFactoryBean">   < Propertyname= "Target"ref= "Impl"></ Property>   < Propertyname= "Interceptornames"value= "before"></ Property>   </Bean></Beans>

However, the flexibility of using the code above is not high: The reason is that you cannot specify which business method to configure the enhanced code before (or after)

Inject this code into the configuration file: Configure Advisor to wrap advice to configure various enhancement types

<!--03. Configure Advisor Advisor Packaging Advice -    <BeanID= "Beforeadvisor"class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor">      < Propertyname= "Advice"ref= "Beforeadvice"></ Property>     < Propertyname= "pattern"value= ". *do.*"></ Property>    </Bean>

4: Of course Spring integrates another way to implement AOP programming: ASPECTJ

Slice class:

 Package CN.HAPPY.AOP; Import Org.aspectj.lang.annotation.Aspect; Import Org.aspectj.lang.annotation.Before; // Ordinary class      @Aspect public classes    myaspect {= "Execution (* *). Service.*.* (..)) " )    publicvoid  Mybeforeadvice () {        System.out.println ("= = Before ");}    }

Configuration file: So simple

<Aop:config>      <Aop:pointcutexpression= "Execution" (* *). Someserviceimpl.dolog (..)) "ID= "Beforepointcut"/>      <Aop:aspectref= "Myaspect">          <Aop:beforeMethod= "Mybefore (org.aspectj.lang.JoinPoint)"Pointcut-ref= "Beforepointcut"/>      </Aop:aspect>   </Aop:config>

Using the spring approach to implement AOP programming

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.