SPRINGAOP implementation (principle)

Source: Internet
Author: User
Tags throwable

AOP principle: AOP is divided into: JDK dynamic agent and Cglib proxy static proxy: The programmer creates or the specific tool automatically generates the source code, and then compiles it.             Before the program runs, the. class file for the proxy classes already exists. Note: The target proxy class cannot be a final field, method, class
Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism. JDK Dynamic Proxy implementation: must have interfaces and implementation classes? Question: Why must be interface and implementation class, since the core is reflection, ordinary Java can also be injected through reflection, why must be interface and implementation class UserService:p ackage COM.GILLION.AOP; /**
*
* @Description Target interface
* @author[email protected]
* @time January 9, 2015 2:28:00
* @version 1.0.0
*/
Public interface UserService {
/**
* Delete users by ID
* @param ID
* @return
*/
public string DeleteUser (string id);
} UserService Realization class:p ackage Com.gillion.aop.impl;
Import Com.gillion.aop.UserService;

/**
* @Description UserService Implementation class
* @author[email protected]
* @time January 9, 2015 2:28:31
* @version 1.0.0
*/
public class Userserviceimpl implements UserService {
public string DeleteUser (string id) {
System.out.println ("Before implementing class modification ID" +id);
SYSTEM.OUT.PRINTLN ("Implementation class modification ID 1111");
Id= "1111";
return ID;
}
} JDK Dynamic Agent implementation: Package Com.gillion.aop; import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy; public class Jdkaop implements Invocationhandler {      //target object    private object target;      /**   * construction method    * @param target object     */   publi C JDKAOP (Object target) {       super ();        this.target = target;  &nbsp ; }     /**   * execute the target object's method    */   public object Invoke (object proxy, Met Hod method, object[] args) throws Throwable {    system.out.println ("------------------ Before------------------ID: "+args[0]);     //A simple print before the method of the target object is executed        SYSTEM.OUT.PRINTLN ("------------------ Before------------------");        SYSTEM.OUT.PRINTLN ("Modify the first parameter to DDFF");     args[0]= "DDFF";     //methods of executing target objects        Object result = Method.invoke (target, args); &n Bsp     SYSTEM.OUT.PRINTLN ("Result returned:" +result);      SYSTEM.OUT.PRINTLN ("Modify Result: DDFDFD");      result= "DDFDFD";     //After the method of the target object is executed, simply print it        SYSTEM.OUT.PRINTLN ( "-------------------after------------------");               return result;   }    /**   * get the target object's proxy object    * @return proxy object    */   PU Blic Object GetProxy () {       return proxy.newproxyinstance (Thread.CurrentThread (). Getcontextclassloader (),                Target.getclass (). Getinterfaces (), this );   } }  

Test class:

Package COM.GILLION.AOP; Import Com.gillion.aop.impl.UserServiceImpl; public class Testjdkaop {public static void main (String []ages) {//Instantiate target object UserService userservice = new Userserv              Iceimpl ();              Instantiate Invocationhandler JDKAOP Invocationhandler = new JDKAOP (userservice);       Generates a proxy object based on the target object UserService proxy = (userservice) invocationhandler.getproxy ();     String id= "333";     System.out.println ("Pre-Call ID:" +id);     Method Id=proxy.deleteuser (ID) to invoke the proxy object; System.out.println ("Post-Call ID:" +id);}} Result: Before calling id:333------------------before------------------id:333------------------ Before------------------modify the first parameter to DDFF implement class modification ID before DDFF implementation class modification ID 1111 result returned: 1111 The result of the modification is: DDFDFD-------------------after---------------- --ID:DDFDFD after call Cglib Dynamic Agent:
The dynamic agent mechanism of JDK can only implement the class of the interface, and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK, the cglib is to implement the proxy for the class, his principle is to generate a subclass for the target class, and overwrite the method implementation enhancement, but because inherit is adopted, Therefore, the final decorated class cannot be proxied. Common Java class: Book Package com.gillion.aop.cglib;

/**
* @Description Book Plain Java
* @author[email protected]
* @time January 9, 2015 2:51:40
* @version 1.0.0
*/
public class Book {
public string test (string id)
{
System.out.println ("Book Change ID before ID:" +id);
Id= "123456";
System.out.println ("Book Changes id=123456");
return ID;
}
} Proxy class: Bookcglib Package com.gillion.aop.cglib;

Import Java.lang.reflect.Method;

Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.MethodInterceptor;
Import Net.sf.cglib.proxy.MethodProxy;

/**
* @Description cglib Agent book (plain java)
* @author[email protected]
* @time January 9, 2015 3:17:03
* @version 1.0.0
*/
public class Bookcglib implements Methodinterceptor {
Private Object target;

/**
* Create proxy object
*
* @param target
* @return
*/
public object getinstance (object target) {
This.target = target;
Enhancer enhancer = new enhancer ();
Enhancer.setsuperclass (This.target.getClass ());
callback method
Enhancer.setcallback (this);
Create a proxy object
return Enhancer.create ();
}

callback method
public object intercept (object obj, Method method, object[] args,
Methodproxy proxy) throws Throwable {
System.out.println ("Cglib things Start");
System.out.println ("Cglib sets the first parameter to 1");
if (args!=null)
args[0]= "1";
Object result=proxy.invokesuper (obj, args);
System.out.println ("After the CGLIB call---Return the result:" +result);
System.out.println ("Cglib change return Result: 654321");
result= "654321";
System.out.println ("Cglib things End");
return result;


}

} Test class: Package com.gillion.aop.cglib;          public class Testcglib {public static void main (string[] args) {bookcglib cglib=new bookcglib ();          Book bookcglib=-Cglib.getinstance (new book ());        String id= "DD";        SYSTEM.OUT.PRINTLN ("No pre-Call ID:" +id);    Bookcglib.test (ID); }  }

SPRINGAOP implementation (principle)

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.