Implement simple AOP framework functionality in Java

Source: Internet
Author: User

Objective
原创文章欢迎转载,请保留出处。若有任何疑问建议,欢迎回复。邮箱:[email protected]

By writing a factory class Beanfactory is responsible for creating an instance object of the target class or proxy class specified in the configuration file Config.properties, the method in the class Getbean returns a corresponding instance object based on the string passed in by the parameter, if the class name is a Proxyfactorybean class, creates The instance object of the proxy class, otherwise directly invokes the target class's constructor without parameters to create an instance object and returns it, implementing the AOP functionality similar to the Spring framework.

Beanfactory class analysis and code

This class is primarily constructed to pass in an input stream receive configuration file, and the other main method Getbean is the core of the entire framework. This method first obtains the name of the class that needs to be created in the configuration file, and then calls the constructor without parameters to create an instance object (the required class in the configuration must be javabean, otherwise it does not necessarily have a constructor without parameters). The instance object is used to determine if it is a Proxyfactorybean object, and if it is, it is converted to a Proxyfactorybean object, calling the method GetProxy in the Proxyfactorybean class to create a proxy object.

 PackageMaxwell_nc.aopframework;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.util.Properties; Public  class beanfactory {Properties props =NewProperties (); Public beanfactory(InputStream IPs) {Try{props.load (IPS);//Read into the configuration file}Catch(IOException e)        {E.printstacktrace (); }    } PublicObjectGetbean(String key) {//The purpose of this method is to obtain a class object referred to by a key,        //If the class is a Proxyfactorybean class, which is the proxy class, the proxy object is created and returned        //If not directly call the constructor without parameters to create an object to returnString clazzname = Props.getproperty (key); Object Bean =NULL;Try{Class clazz = Class.forName (clazzname); Bean = Clazz.newinstance ();//For JavaBean must have a method of constructing without parameters}Catch(Exception e)        {E.printstacktrace (); }if(BeaninstanceofProxyfactorybean) {//Convert to Proxyfactorybean object, easy to use GetProxy method and set methodProxyfactorybean Proxyfactorybean = (Proxyfactorybean) bean; Object proxy =NULL;Try{//Get the object target and advice class that you want to establishObject target = Class.forName (Props.getproperty (key+". Target"). newinstance (); Advice ad = (Advice) class.forname (Props.getproperty (key+". Advice"). newinstance ();                Proxyfactorybean.settarget (target);                Proxyfactorybean.setad (AD);            Proxy = Proxyfactorybean.getproxy (); }Catch(Exception ex)            {Ex.printstacktrace (); }returnProxy }returnBean }}
Proxyfactorybean class analysis and code

The core is that GetProxy uses the static method of the proxy class newproxyinstance to create the proxy object, overwriting the Invoke method, and using the Invocationhandler processing method call. The advice implementation class is inserted in the middle of the Invoke method.

 PackageMaxwell_nc.aopframework;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Proxy;ImportJava.lang.reflect.Method; Public  class proxyfactorybean {    PrivateObject Target;PrivateAdvice AD; PublicObjectGetProxy() {//Use static method of proxy class Newproxyinstance to create proxy objectObject proxyobj = proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). GetInterface S (),NewInvocationhandler () { PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {Ad.beforemethod (method);                Object obj = Method.invoke (target, args); Ad.aftermethod (method);returnObj }        }                   );returnProxyobj; } PublicObjectGettarget() {returnTarget } Public void settarget(Object target) { This. target = target; } PublicAdviceGetAd() {returnAd } Public void Setad(Advice AD) { This. AD = AD; }}
Advice interface and implementation class

This does not have to parse, directly to the code, advice interface

package maxwell_nc.aopframework;import java.lang.reflect.Method;publicinterface Advice {    void beforeMethod(Method method);    void afterMethod(Method method);}

Advice Implementation class

package maxwell_nc.aopframework;import java.lang.reflect.Method;public class MyAdvice implements Advice { @Override public void afterMethod(Method method) { System.out.println(method.getName()+"_start"); } @Override public void beforeMethod(Method method) { System.out.println(method.getName()+"_end"); }}
Test classes and configuration files

Here we use a separate class to test, we first write a config.properties file

#bean=java.util.ArrayListbean=maxwell_nc.aopframework.ProxyFactoryBeanbean.target=java.util.ArrayListbean.advice=maxwell_nc.aopframework.MyAdvice

Note that if you use the first line to represent a normal bean, the second row creates a Proxyfactorybean, which you can test separately. Here is the test class

 PackageMaxwell_nc.aopframework;ImportJava.io.InputStream;ImportJava.util.Collection; Public  class aopframeworktest {     Public Static void Main(string[] args) {InputStream ips = AopFrameworkTest.class.getResourceAsStream ("Config.properties");//Create a factoryBeanfactory beanfactory =NewBeanfactory (IPS);//Get the object and print the corresponding byte code nameObject Bean = Beanfactory.getbean ("Bean"); System.out.println (Bean.getclass (). GetName ());//The following statement can test whether the advice class is valid        //((Collection) bean). Clear ();}}

We try to create the proxy object and test the result in MyEclipse: The proxy object is obtained normally and the advice class function is called.

Summarize

In fact, Proxyfactorybean can be defined as an interface, there are many bean classes that implement this interface, each of which is judged, each bean class has its own GetProxy method, more flexible.

Implement simple AOP framework functionality in Java

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.