AOP programming, spring implementation and JDK,CGLIB implementation

Source: Internet
Author: User

What is AOP?

Unlike AOP (aspect-orientedprogramming, aspect-oriented programming) and OOP (object-oriented programing, object-oriented programming), the two are not opposites, the former complements the latter. The latter, because of the former supplement and reduce duplication of code, so that the program reduces the coupling between modules, increase the operability of future code and maintainability.

Why use AOP mode?

If we need to record statistics on the invocation of methods in the object in the business logic, we usually need to add a new method to each class to complete the corresponding share, so there will be a lot of duplicated parts in the code, and the program will be highly coupled and difficult to maintain.

AOP Main Features:

Main functions: Logging, performance statistics, security control, transaction processing, exception handling and so on. AOP is primarily about dividing these functions from business logic code, and by separating them, we want to be able to separate them into non-instructional methods of business logic, and then change these behaviors without affecting the code of the business logic.

Let's take a quick look at how to implement AOP programming in spring.

Implementation of AOP in spring can be made with annotations and configuration XML in two modes.

Let's take a look at how annotations are implemented.

First we need an interface, and the class that implements it.

Interface:

 Public Interface Personservice {    public  String getpersonname (Integer ID);      Public void Save (String name);}

Implementation class:

 public  class  Personservicebean Span style= "color: #0000ff;" >implements   Personservice {@Override    String Getpersonname (Integer id) { //  TODO auto-generated method stub  retur    n  null   public  void   Save (String name) { //  TODO Auto-genera    Ted Method Stub  System.out.println ("you entered" + name); }    }

Then we need to configure the XML file, and we need to give the business bean to spring to manage

Xml:

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"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-2.5. XSD Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring -context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/s Pring-aop-2.5.xsd ">    <Aop:aspectj-autoproxyProxy-target-class= "true"/>    <BeanID= "Myinterceptor"class= "Cn.qdlg.service.MyInterceptor"></Bean>    <BeanID= "Personservice"class= "Cn.qdlg.service.impl.PersonServiceBean"></Bean></Beans>

Next we need to complete intercept class definition facets and pointcuts

 Public classmyinterceptor {@Pointcut ("Execution (* cn.qdlg.service.impl.personservicebean.* (..))")     Public voidAnymethod () {} @Before ("Anymethod ()")     Public voidDoaccesscheck (String name) {System.out.println ("Pre-notification" +name); } @AfterReturning ("Anymethod () && args (name)")     Public voidDoafterreturn (String result) {System.out.println ("Post Notification" +result); } @After ("Anymethod ()")     PublicObject Doafter (Proceedingjoinpoint PJP)throwsthrowable{System.out.println ("Access Method"); Object result=pjp.proceed (); System.out.println ("Final Notice"); returnresult; } @AfterThrowing ("Anymethod ()")     Public voiddoafterthrowing (Exception e) {System.out.println ("Exception notification" +e); } @Around ("Anymethod ()")     Public voidDoaround () {System.out.println ("Surround Notifications"); }}

Finally, we can write a test method that invokes the method of the intercepted class.

If it is an XML configuration implementation:

You need to configure facets and pointcuts in the configuration file

Add the following code to the original XML file

<Aop:config>        <Aop:aspectID= "ASP"ref= "Myinterceptor">            <Aop:pointcutID= "Mycut"expression= "Execution (* cn.qdlg.service.impl.personservicebean.* (..))"/>            <Aop:beforePointcut-ref= "Mycut"Method= "Doaccesscheck"/>            <Aop:afterPointcut-ref= "Mycut"Method= "Doafter"/>            <aop:after-returningPointcut-ref= "Mycut"Method= "Doafterreturn"/>            <Aop:aroundPointcut-ref= "Mycut"Method= "Doaround"/>            <aop:after-throwingPointcut-ref= "Mycut"Method= "Doafterthrowing"/>        </Aop:aspect></Aop:config>

Implementation of AOP with the JDK agent and cglib agent in spring

JDK Dynamic agent only for class generation agents that implement an interface
The Cglib proxy implements the proxy for the class, primarily a subclass of the specified class, overwriting all of them, and the method of that class cannot be declared final
If the target does not implement an interface, the Cglib proxy is used by default

Let's look at how the JDK and cglib agents implement the JDK proxy

 Public classJdkproxyfactoryImplementsinvocationhandler{PrivateObject TargetObject;  PublicObject Creatproxyfactory (Object targetobject) { This. TargetObject =TargetObject; returnProxy.newproxyinstance ( This. Targetobject.getclass (). getClassLoader (), This. Targetobject.getclass (). Getinterfaces (), This); } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {Personservicebean bean= (Personservicebean) This. TargetObject; Object result=NULL; if(Bean.getpersonname ()! =NULL) {result=Method.invoke (TargetObject, args); }        returnresult; }}

Cglib Agent

 Public classCglibproxyfactoryImplementsMethodinterceptor { PublicObject TargetObject;  PublicObject Creatproxyintance (Object targetObject) { This. TargetObject =TargetObject; Enhancer Enhancer=Newenhancer (); Enhancer.setsuperclass ( This. Targetobject.getclass ()); Enhancer.setcallback ( This); returnenhancer.create (); }         PublicObject Intercept (Object Proxy,method method,object[] args, methodproxy methodproxy)throwsthrowable{Personservicebean Bean= (Personservicebean) This. TargetObject; Object result=NULL; if(Bean.getpersonname ()! =NULL) {result=Methodproxy.invoke (TargetObject, args); }        returnresult; }}

AOP programming, spring implementation and JDK,CGLIB implementation

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.