Spring Framework AOP (iii)

Source: Internet
Author: User

An overview of AOP theory

Aspect oriented programming programming for facets
Industry AOP is actually an extension of OOP (object-oriented programming)-OOP programming language, AOP design idea

AOP takes the horizontal extraction mechanism instead of the traditional vertical inheritance system repetitive code ( performance monitoring, transaction management, security check, caching )

Horizontal extraction of code reuse, based on agent technology, without modification of the original object code, the original object method function to enhance! ———-the idea of AOP

How the Spring framework implements AOP
Spring1.2 version begins to support AOP technology (traditional spring AOP)

After Spring2.0, to simplify AOP development, start supporting the AspectJ (third-party framework) AOP framework

Learning Focus: AspectJ AOP Development

1.3.AOP related terms
1.Joinpoint (connection point): The so-called connection point refers to the points that are intercepted. In spring, these points refer to methods because spring only supports connection points of method types.
2.Pointcut (entry point): The so-called entry point refers to which joinpoint we want to intercept the definition.
3.Advice (Notification/enhancement): The so-called notification refers to the interception to Joinpoint after the thing to do is to inform. Notification is divided into pre-notification, post-notification, exception notification, final notification, surround notification (section to complete the function)
4.Introduction (Introduction): Introduction is a special kind of notification without modifying the class code, Introduction can dynamically add methods or field to the class at run time.
5. Targetobject: The target object of the agent
6.Weaving (weaving): Refers to the process of applying an enhancement to a target object to create a new proxy object.
7.spring is woven with dynamic agents, while the ASPECTJ is woven in at compile-time and class-loading stages
8.Proxy: When a class is augmented by AOP, it produces a result proxy class
9.Aspect (tangent): A combination of entry point and notification (referral)

AOP Bottom-up implementation

Spring AOP proxy implementations are available in two ways: JDK dynamic agent and cglib framework Dynamic Agent

JDK Dynamic Agent
JDK API built-in proxy class to create proxies for target objects (interface agent must be oriented)

 Public  class jdkproxyfactory implements Invocationhandler {    //proxy object    PrivateObject Target;//When constructing a method object, the incoming proxy object     Public jdkproxyfactory(Object target) { This. target = target; }//Create an agent     PublicObjectCreateproxy() {///Three parameters: Class loader, implementation interface, Invocationhandler        returnProxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), This); }@Override     PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {System.out.println (the logging!!!!!! ");//Call the target real method        //target is the proxy object, the args method parameter, method is called        returnMethod.invoke (target, args); }}

Cons: Using the JDK dynamic proxy, you must require the target object to implement the interface, and if there is no interface, you cannot use the JDK dynamic proxy.

Cglib Dynamic Agent
CGLIB (Code Generation Library) is an open source project! is a powerful, high-performance, high-quality code generation class library that can extend Java classes and implement Java interfaces at run time.

Cglib can not only proxy the interface, but also to the target class object, to implement the proxy (the JDK can only solve the interface agent problem)
Download URL: http://sourceforge.net/projects/cglib/files/
——-built-in Cglib class in spring3.2 version core package

 Public  class cglibproxyfactory implements methodinterceptor {    //Agent target object    PrivateObject Target;//Passing in the Proxied object when constructing the factory     Public cglibproxyfactory(Object target) { This. target = target; }//Create proxy object method     PublicObjectCreateproxy() {///1, create enhancer objectEnhancer enhancer =NewEnhancer ();///2, Cglib Create the proxy, target object, create subclass objectEnhancer.setsuperclass (Target.getclass ());///3, incoming callback object, enhanced for targetEnhancer.setcallback ( This);returnEnhancer.create (); }@Override     PublicObjectIntercept(Object proxy, method, object[] args, Methodproxy methodproxy)throwsThrowable {System.out.println ("Logging ...");//Follow JDK programming        returnMethod.invoke (target, args); }}

Cglib Creating a proxy idea: creating subclass objects on target classes
Set superclass to which class to create subclasses (similar to JDK proxy interface)
Set callback implementation enhancement code (similar to JDK proxy invocationhandler)

In Cglib's callback function, the method to execute the Proxied object
Method.invoke (target, args); Equivalent to Methodproxy.invokesuper (proxy, args);

Priority to the interface agent (using the JDK proxy), if the target does not have an interface, the Cglib agent will be used!

Spring AOP Programming

Traditional SPRINGAOP notification type (Spring1.2 version start)
First: AOP Federation defines the ADVICE notification interface
Org.aopalliance.aop.Interface.Advice
Then: Spring AOP expands to five notification types based on the advice interface

Introducing pointcut pointcut definitions through ASPECTJ
Step one: Implement AOP programming, introduce a jar package in a project
? Com.springsource.org.aopalliance-1.0.0.jar AOP Federation definition Specification JAR Package
? Spring-aop-3.2.0.release.jar Spring Object AOP Advice extension
? Com.springsource.org.aspectj.weaver-1.6.8.release.jar ASPECTJ Framework jar Package
? Spring-aspects-3.2.0.release.jar Spring to ASPECTJ support jar package

Step Two: Configure the file to introduce an AOP namespace

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

Step Three: Write advice

/** * custom surround notification (traditional spring AOP Advice) * * @author  seawind * */ public  class  mymehtodinterceptor  implements  methodinterceptor  { Span class= "hljs-annotation" > @Override public  Object invoke  (methodinvocation methodinvocation) throws  Throwable {S Ystem.out.println ( "surround the front enhancement ====================" ); //call target method  Object result = Methodinvocation.proceed (); System.out.println ( "surround enhanced ====================" ); return  result; }}

Fourth step: Define Pointcut Facets

Execution (* cn.itcast.service). . (..)) The Intercept service package contains all the methods under the sub-package all classes
Execution (* . s(..)) intercept methods that begin with S

<!--Configuring target objects --    <bean id="OrderService" class="Cn.itcast.spring.c_aop". Orderserviceimpl " />    <!--Configuring custom advice (Traditional)--    <bean id="Mymethodadvice" class="Cn.itcast.spring.c_aop . Mymehtodinterceptor " />    <!--configuring facets --    <!--for AOP-related configuration -    <aop:config>        <!--aop:advisor: Defines the facets of spring's traditional AOP, supports only one pointcut and one advice Aop:aspect: Defines the ASPECTJ frame facets, which can be To contain multiple pointcut and multiple advice aop:pointcut: Tangent definition --         <aop:pointcut expression="Execution (* cn.itcast.spring.c_aop. orderserviceimpl.* (..)) " id="Mypointcut"/>         <aop:advisor advice-ref= "mymethodadvice" pointcut-ref=" Mypointcut "/>    </aop:config>

Summarize:
AOP Advisor = = = Traditional Spring AOP Advice (one) + tangent point (one)

AspectJ AOP Programming

AspectJ is a framework (third-party AOP framework) that provides slicing programming, writing a aspect to support multiple advice and multiple pointcut.

AspectJ Notification Type

One more after final notification than the spring notification type

before front-facing notification
To enhance code before the target method executes
AspectJ provides advice without any excuse to write many of the notification code to a class (slice Class)
Predecessor notification definition method: No return value, can pass in parameter Joinpoint connection point

publicclass MyAspect {    publicvoidbefore1() {        System.out.println("前置通知 1.....");    }

Details:
1, the default does not prevent the target method execution, if the exception is thrown, the target method cannot execute
2, can pass the Joinpoint connection point parameter, through this parameter can obtain the current interception object and the method information

    <!--configuration targets --    <bean id="CustomerService" class="Cn.itcast.spring.d_aspectj". CustomerService " />    <!--configuring slice beans --    <bean id="Myaspect" class="Cn.itcast.spring.d_aspectj". Myaspect " />    <!--AOP facets configuration --    <aop:config>        <!--ref reference define slice class --        <aop:aspect ref="Myaspect">            <aop:pointcut expression="Execution (* cn.itcast.spring.d_aspectj. customerservice.* (..)) " id="Mypointcut2"/>            <aop:before Method="Before1" pointcut-ref="Mypointcut2" />            <aop:before Method="Before2" pointcut-ref="Mypointcut2"/>         </aop:aspect>    </aop:config>

afterreturning post-placement notification
Code enhancement after the execution of the target business method

// 可以在后置通知传入两个参数 1、 连接点对象 2、目标方法返回值    publicvoidafterReturning(JoinPoint joinPoint, Object result) {        System.out.println("后置通知.... 目标方法运行返回值 :" + result);    }
<!-- returning参数,定义后置通知 接收目标方法返回值 参数名称 --><aop:after-returning method="afterReturning" returning="result2" pointcut-ref="mypointcut2"/>

Details:
The post-notification can get the return value of the method, and the parameter name in the configuration file definition return value must be the same as the method parameter name.

Around Surround Notification
Code enhancements before and after the target method executes (blocks the execution of the target method)
Surround notifications for any notification effect

//surround notification (need to return the target method return value), incoming parameters The connection point can be executed  public  Object around  ( Proceedingjoinpoint proceedingjoinpoint) throws Throwable {System.        Out . println (//execution target method  System. out . println ( "wrapping notification method after execution ....)        Method return Value: " + result";    return  result; }
<!-- 环绕通知 --><aop:around method="around" pointcut-ref="mypointcut2" />

afterthrowing Throw Notification
Notification method is executed after the target method has an exception--Error logging

// 日志记录器    privatestatic final Logger LOG = Logger.getLogger(MyAspect.class);    // 抛出通知    // 第一个参数 JointPoint 连接点    // 第二个参数 目标方法出现异常后,捕获到异常对象    publicvoidafterThrowing(JoinPoint joinPoint, Throwable ex) {        System.out.println("哪个方法出现异常:" + joinPoint.toLongString());        // 调用日志记录API,将异常对象 写入日志文件        LOG.error(ex.getMessage(), ex);    }

Method receives two parameter connection points and exception objects

<!-- 异常通知 -->            <!-- throwing属性,配置发生异常后,捕获的异常对象参数名称 (和方法一致) -->            <aop:after-throwing method="afterThrowing" throwing="ex" pointcut-ref="mypointcut2"/>

After final notification
The notification executes regardless of whether the target method has an exception-similar to the finally code block
Application Scenario: Freeing resources

// 最终通知    publicvoidafter(JoinPoint joinPoint) {        System.out.println("最终通知... 释放资源.... ");    }
<!-- 最终通知 -->            <aop:after method="after" pointcut-ref="mypointcut2" />

Spring Framework AOP (iii)

Related Article

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.