Simulate spring-write a spring AOP

Source: Internet
Author: User

I. Preface

AOP (Aspect Oriented Programing)-it is mainly used for log recording, performance analysis, security control, transaction processing, Exception Processing, and so on.

AOP mainly uses JDK reflection and dynamic proxy. The AOP proxy is actually an object dynamically generated by the AOP framework and can be used as the target object, the AOP proxy contains all the methods of the target object, but the methods of the AOP proxy differ from those of the target object: The AOP method adds enhanced processing to a specific entry point, the method of the target object is called back.

 

 

II. Implementation Details

The following example uses AOP to implement logging:

Attached to the structure of a class, this example needs to import dom4j. jar

 

① Business logic interface

 

/*** Business logic interface * @ author zhangjim */public interface BusinessService {/*** process the business */public void process ();}
② Business logic implementation

 

 

/*** Business logic object implementation class * @ author zhangjim */public class BusinessServiceImpl implements BusinessService {/*** process Business */public void process () {System. out. println (process business logic ...);}}
③ Notification Interface

 

 

/*** Notification interface ** @ author zhangjim */public interface Advisor {/*** operations */public void doInAdvisor (Object proxy, Method method, object [] args );}
④ Method pre-notification

 

 

Import java. lang. reflect. method;/*** Method pre-notification, it completes the pre-operation of the Method * @ author zhangjim */public class BeforeMethodAdvisor implements Advisor {/*** operations before the method is executed */public void doInAdvisor (Object proxy, method method, Object [] args) {System. out. println (before process ...);}}
⑤ Post-notification of the Method

 

 

/*** Post-notification of the method, it completes the post-operation * @ author zhangjim */public class AfterMethodAdvisor implements Advisor {/*** operations performed after the method is executed */public void doInAdvisor (Object proxy, method method, Object [] args) {System. out. println (after process ...);}}
⑥ AOP Processor

 

 

Import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; import com. zdp. advisor. advisor;/*** AOP processor * @ author zhangjim */public class AopHandler implements InvocationHandler {private Object target; // the target Object that requires proxy Advisor beforeAdvisor; // method pre-notification Advisor afterAdvisor; // method post-notification/*** sets the proxy target object and generates a dynamic proxy object. * @ param target proxy target object * @ return dynamic proxy object */public O Bject setObject (Object target) implements this.tar get = target; // sets the proxy target Object Proxy = proxy. newProxyInstance (target. getClass (). getClassLoader (), target. getClass (). getInterfaces (), this); // generate a dynamic proxy object return proxy Based on the proxy target object;}/*** if pre-processing is defined, perform the pre-processing before the method is executed, if post-processing is defined, post-processing is called after the method is called. ** @ param proxy Object * @ param method the business method called * @ param args parameter * @ return returned result information * @ throws Throwable */public Object invoke (Objec T proxy, Method method, Object [] args) throws Throwable {if (beforeAdvisor! = Null) {beforeAdvisor. doInAdvisor (proxy, method, args); // pre-processing of Business Methods} method. invoke (target, args); // executes the business method if (afterAdvisor! = Null) {afterAdvisor. doInAdvisor (proxy, method, args); // post-processing of Business Methods} return null; // returned result object}/*** pre-notification for setting method * @ param advisor method pre-notification */public void setBeforeAdvisor (Advisor advisor) {this. beforeAdvisor = advisor;}/*** post notification for setting method * @ post notification for param advisor Method */public void setAfterAdvisor (Advisor advisor) {this. afterAdvisor = advisor ;}}
7. Bean Factory

 

 

Import java. io. inputStream; import java. util. hashMap; import java. util. iterator; import java. util. map; import org. dom4j. attribute; import org. dom4j. document; import org. dom4j. element; import org. dom4j. io. SAXReader; import com. zdp. advisor. advisor;/*** Bean factory class * @ author zhangjim */public class BeanFactory {private Map
 
  
BeansMap = new HashMap
  
   
();/*** Bean Factory initialization */public void init (String xml) {try {SAXReader reader = new SAXReader (); ClassLoader classLoader = Thread. currentThread (). getContextClassLoader (); InputStream ins = classLoader. getResourceAsStream (xml); // read the specified configuration file Document doc = reader. read (ins); Element root = doc. getRootElement (); AopHandler aopHandler = new AopHandler (); // create an AOP processor (reference of aopHandle is held in the dynamically generated proxy class) for (Iterator ite R = root. elementIterator (bean); iter. hasNext ();) {// traverse bean Element element = (Element) iter. next (); Attribute id = element. attribute (id); // obtain the bean attribute id, class, aopClass, and aopTypeAttribute cls = element. attribute (class); Attribute aopClass = element. attribute (aopClass); Attribute aopType = element. attribute (aopType); if (aopClass! = Null & aopType! = Null) {// If the aopClass and aopType attributes are configured, the interception operation Class advisorClass = Class is required. forName (aopClass. getText (); // obtain the corresponding class Advisor = (advisor) advisorClass according to the aopClass string. newInstance (); // create the object if (before. equals (aopType. getText () {// set the front or back consultant aopHandler Based on the aopType. setBeforeAdvisor (advisor);} else if (after. equals (aopType. getText () {aopHandler. setAfterAdvisor (advisor);} Class clazz = Class. forName (cls. getText (); // use the Java reflection mechanism to obtain the class Object obj = clazz through the Class name. newInstance (); // create an Object proxy = (Object) aopHandler. setObject (obj); // generate the proxy object proxybeansMap. put (id. getText (), proxy); // put the object into beansMap, where id is key and object is value }}catch (Exception e) {System. out. println (e. toString () ;}}/*** get the bean object through the bean id. * @ param beanName bean id * @ return returns the corresponding Object */public Object getBean (String beanName) {Object obj = beansMap. get (beanName); return obj ;}}
  
 
Secret configuration file beans. xml

 

 
 
  
 

 

Testing

 

 

Import com. zdp. service. businessService; import com. zdp. spring. beanFactory;/*** test class * @ author zhangjim */public class Client {public static void main (String [] args) {BeanFactory beanFactory = new BeanFactory (); beanFactory. init (beans. xml); BusinessService proxy = (BusinessService) beanFactory. getBean (businessService); proxy. process ();}}

 

 

Iii. Summary

The above is just a simple simulation of the implementation of spring's AOP, but it still shows the application of JDK reflection and dynamic proxy in spring. It should be helpful for beginners to understand AOP.

 

Source code: http://download.csdn.net/detail/zdp072/7284987

References: http://www.ibm.com/developerworks/cn/java/j-lo-springaopcglib/


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.