Java reflection-simulating spring's AOP

Source: Internet
Author: User

1. Approximate process

The previous article has explained the principle of SPRINGAOP with Java reflection, where we simply simulate the following spring AOP implementations. The general flow is as follows:

? Create a properties profile to simulate the spring configuration file.

? Create an enhanced interface with an implementation class that simulates spring's advice.

? Create a factory class for the build agent and weave the enhancement method (that is, AOP) into the Invoke method of the Invocationhandler class.

? Create a factory class that generates beans (like the IOC factory, which only creates beans, does not have dependency injection), when the bean is generated, if it is a spring-managed class, the target object's proxy object is returned, and if the class is not spring-managed, the target object is returned directly. theory no longer says, look directly at the code:

2. Instance Code2.1 configuration file (config.properties):
#1, simulating classxxx=java.util.arraylist#2 of beans not managed by spring, simulating class#xxx= of beans managed by spring Cn.itcast.day3.aopframework.proxyfactorybean#3, XXX's enhanced class xxx.advice=cn.itcast.day3.aopframework.myadvice#4, XXX Target class Xxx.target=java.util.arraylist

2.2 Enhanced Interface:
Package Cn.itcast.day3.aopframework;import java.lang.reflect.method;/** * Enhanced interface *  * @author Wangzhipeng * */  Public interface Advice {//Pre-enhancement method void Beforemethod (method);//post-enhancement method void Aftermethod (method);}

2.3 Enhanced implementations:
Package Cn.itcast.day3.aopframework;import java.lang.reflect.method;/** * Enhanced class *  * @author Wangzhipeng * */  public class Myadvice implements Advice {Long beginTime = 0;/** * Pre-enhancement method */public void Beforemethod (Method method) {System . OUT.PRINTLN ("to TGB to learn!") "); beginTime = System.currenttimemillis ();} /** * Post-enhancement method */public void Aftermethod (method) {System.out.println ("graduated from TGB to work!") "); Long endTime = System.currenttimemillis (); System.out.println (Method.getname () + "Running Time of" + (Endtime-begintime));}}

2.4 Factory class for the build agent:
Package Cn.itcast.day3.aopframework;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.Method; Import java.lang.reflect.proxy;/** * Build Agent Factory class * * @author Wangzhipeng * */public class Proxyfactorybean {//Enhanced object Private Advice advice;//target object Private object target;//Gets the target object's proxy object public Object GetProxy () {Object proxy = Proxy.newproxyinstance ( Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), new Invocationhandler () {// The anonymous inner class of the Invocationhandler interface, or any method that executes the proxy object, is replaced with the following Invoke method public object invoke (object proxy, method, object[] args) throws Throwable {Advice.beforemethod (method);//perform "front" enhancement Method Object RetVal = Method.invoke (target, args);// Executes the target method Advice.aftermethod,//Executes the "POST" enhancement method return retval;//Returns the target method execution result, the proxy object's method return value must be the same as the method return value of the target object}); return Proxy;} Public Advice Getadvice () {return Advice;} public void Setadvice (Advice Advice) {this.advice = Advice;} Public Object Gettarget () {return target;} public void Settarget (Object target) {this.target = Target;}} 

2.5 Generating The Bean's factory class (like the IOC factory, where you can only create beans, no dependency injection)
Package Cn.itcast.day3.aopframework;import Java.io.ioexception;import Java.io.inputstream;import java.util.properties;/** * Simulates spring's IOC factory (only provides creation bean function, cannot rely on injection) * * @author Wangzhipeng * */public class Beanfactory {Prop Erties props = new Properties ();/** * When instantiating a bean factory, we scan our configuration file (incoming profile) * * @param the Stream stream of the IPs * configuration file */public B Eanfactory (InputStream IPs) {try {props.load (IPS);} catch (IOException e) {e.printstacktrace ();}} /** * Production Bean * * @param name * Bean names */public Object Getbean (string name) {String className = Props.getprope Rty (name); object Bean = null;try {///reflection Gets the class name name of the subject class Clazz = Class.forName (className); bean = Clazz.newinstance ();} CA TCH (Exception e) {e.printstacktrace ();} If the target is managed by spring (where the bean is substituted for an object of type Proxyfactorybean), the target's proxy object is returned, or the target object is returned directly//the actual spring, You can use spring's configuration file or annotations to determine if spring manages if (bean instanceof Proxyfactorybean) {Object proxy = null; Proxyfactorybean Proxyfactorybean = (Proxyfactorybean) bean;try {//Reflection get enhanced object advice advice = (advice)Class.forName (Props.getproperty (name + ". Advice")). newinstance ();//reflection Gets the target objects object target = Class.forName ( Props.getproperty (name + ". Target")). newinstance ();//Generate a proxy object for the target object, and weave the enhancement method to achieve the Aopproxyfactorybean.setadvice (advice );p Roxyfactorybean.settarget (target);p roxy = Proxyfactorybean.getproxy ();} catch (Exception e) {e.printstacktrace ();} Return proxy;//returns the target's proxy object if the target is managed by spring}return bean;//if not managed by spring, return directly to the target}}

2.6 Test Class
Package Cn.itcast.day3.aopframework;import java.io.inputstream;/** * Test class *  * @author Wangzhipeng *  */public Class Aopframeworktest {public static void main (string[] args) throws Exception {//get the stream stream of the configuration file inputstream ips = Aopfra MeworkTest.class.getResourceAsStream ("config.properties");//Use the Bean factory to create an object of the class configured in the configuration file, the objects bean = new Beanfactory ( IPS). Getbean ("xxx");//test beanfactory whether the target or proxy is generated, and if the agent executes the enhanced Method System.out.println (Bean.getclass (). GetName ()); Bean.hashcode ();}}

2.7 Test result 1:

If "Xxx=cn.itcast.day3.aopframework.proxyfactorybean" is configured in the configuration file, the result is


  

The description returns a proxy object, and an enhanced method is performed. (because we have the relevant judgment in our Beanfactory "if (Bean instanceof Proxyfactorybean)").

2.8 Test Results 2

If "Xxx=cn.itcast.day3.aopframework.proxyfactorybean" is configured in the configuration file, the result is

  

The description returns the target object, and the enhancement method is not enforced.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java reflection-simulating spring's AOP

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.