[Pin to top] Spring AOP uses JDK invocationhandler to generate dynamic proxy

Source: Internet
Author: User

Notes ......

First, there is an interface userservice

 

package com.spring.test;import org.springframework.stereotype.Component;@Componentpublic interface UserService {public void createUser();public void deleteUser();public void updateUser(int id);}

Userdao implements userservice

 

 

package com.spring.test;import org.springframework.stereotype.Component;@Componentpublic class UserDao implements UserService {public void createUser() {System.out.println("user saved...");}public void deleteUser(){System.out.println("delete user...");}public void updateUser(int id){System.out.println("update user...");}}

 

You want to add some business logic to the execution of these methods, such as public logs or the time before and after the execution of the calculation method, and cut the code into the method in the form of a cut, in this case, you can use a dynamic proxy,

The underlying dynamic proxy of AOP is the proxy and invocationhandler implemented by the dynamic proxy of JDK. java. Lang. Reflect. invocationhandler must be implemented.

First define a loginteceptor to implement invocationhandler:

 

Package COM. spring. log; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; import Java. util. calendar; import Java. util. date; /****************** log class ** @ author administrator **/public class loginteceptor implements invocationhandler {private object target; // The proxy object public object gettarget () {return target;} public void settarget (object target) implements this.tar get = target;} public object invoke (Object proxy, method, object [] ARGs) throws throwable {beforemethod (method); // the business logic to be executed before the method is executed long starttime = system. currenttimemillis (); method. invoke (target, argS); long result = system. currenttimemillis ()-starttime; system. out. println ("execution time:" + Result + "millisecond"); aftermethod (method); // the business logic to be executed after the method is executed return NULL ;} public void beforemethod (method M) {system. out. println (M. getname () + "execute before .... ");} public void aftermethod (method M) {system. out. println (M. getname () + "Run after... ");}}

Then use JUnit for testing.

 

 

Package COM. JUnit. test; import Java. lang. reflect. proxy; import COM. spring. log. loginteceptor; import COM. spring. test. userdao; import COM. spring. test. userservice; public class test {@ Org. JUnit. testpublic void testproxy () {userdao = new userdao (); // The proxy object loginteceptor = new loginteceptor (); // obtain the log invocationhandlerloginteceptor. settarget (userdao); // set the proxy object to userdao // set the proxy object. Parameter 1: classloader of the proxy object, parameter 2: the interface implemented by the proxy object (this object must implement the interface, otherwise it cannot generate a proxy). Parameter 3: Specifies the invocationhandleruserservice userservice = (userservice) proxy to be processed. newproxyinstance (userdao. getclass (). getclassloader (), new class [] {userservice. class}, loginteceptor); userservice. createuser (); // execution method userservice. deleteuser (); // execution method userservice. updateuser (1001); // execution method }}

 

Execution result:

Createuser: Execute before ....
User saved...
--- Execution time: 0 ms
Createuser executes after...
Deleteuser: Execute before ....
Delete user...
--- Execution time: 0 ms
Deleteuser: Execute after...
Updateuser executes before ....
Update user...
--- Execution time: 0 ms
Updateuser executes after...

Next, let's look at the actual ..........................

Define a loginterceptor so that methods in Dao can execute certain specific methods before and after execution.

 

Package COM. spring. log; public class loginterceptor {public void beforemethod () {system. out. println ("execution before method execution");} public void aftermethod () {system. out. println ("executed after method execution ");}}

The defined beforemethod and aftermethod are configured with AOP in applicationcontext. xml.

 

 

<Bean id = "mylog" class = "com. spring. log. loginterceptor "> </bean> <AOP: config> <AOP: aspect id =" log "ref =" mylog "> <AOP: pointcut expression =" execution (* COM. spring. test. *. *(..)) "id =" point "/> <! -- Entry point --> <AOP: Before method = "beforemethod" pointcut-ref = "point"/> <! -- Run the beforemethod defined by yourself before --> <AOP: After method = "aftermethod" pointcut-ref = "point"/> <! -- Execute the custom aftermethod after defining the method --> </AOP: aspect> </AOP: config>

 

You can also configure

 

<aop:around method=""/><aop:after-returning method=""/><aop:after-throwing method=""/>

Finally, use JUnit to test:

 

 

@org.junit.Testpublic void Test(){ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");UserService service = (UserService) ctx.getBean("userDao");service.createUser();}

Execution result:

 

Before method execution
User saved...
Method execution

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.