Java uses dynamic proxies to implement an AOP (logging) Instance code _java

Source: Internet
Author: User
Tags aop sleep string find

Here is a simple example of an AOP implementation:

First, define some business methods:

Copy Code code as follows:

/**
* Created with IntelliJ idea.
* Author:wangjie email:tiantian.china.2@gmail.com
* date:13-9-23
* Time: 3:49
*/
Public interface Bussinessservice {
public string Login (string username, string password);
Public String find ();
}

public class Bussinessserviceimpl implements Bussinessservice {
Private Logger Logger = Logger.getlogger (This.getclass (). Getsimplename ());

@Override
public string Login (string username, string password) {
Return "Login Success";
}

@Override
Public String Find () {
Return "Find success";
}

}




Copy Code code as follows:

/**
* Created with IntelliJ idea.
* Author:wangjie email:tiantian.china.2@gmail.com
* date:13-9-24
* Time: 10:27
*/
Public interface Workservice {
Public String work ();
Public String sleep ();
}

public class Workserviceimpl implements workservice{
@Override
Public String work () {
Return "work success";
}

@Override
Public String sleep () {
Return to "sleep success";
}
}




Implement Invocationhandler interface, use map to store different Invocationhandler objects, avoid generating too much.

Copy Code code as follows:



Package Com.wangjie.aoptest2.invohandler;

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import Java.util.Arrays;
Import Java.util.HashMap;
Import Java.util.logging.Logger;

/**
* Created with IntelliJ idea.
* Author:wangjie email:tiantian.china.2@gmail.com
* date:13-9-23
* Time: 3:47
*/
public class Loginvohandler implements invocationhandler{
Private Logger Logger = Logger.getlogger (This.getclass (). Getsimplename ());

Private Object target; Agent Target
Private Object proxy; Proxy Object

private static Hashmap<class<?>, loginvohandler> invohandlers = new Hashmap<class<?> Loginvohandler> ();

Private Loginvohandler () {
}

/**
* Generate dynamic proxy object proxy via class
* @param clazz
* @return
*/
Public synchronized static<t> T getproxyinstance (class<t> clazz) {
Loginvohandler Invohandler = Invohandlers.get (clazz);

if (null = = Invohandler) {


Invohandler = new Loginvohandler ();


try {


T tar = clazz.newinstance ();


Invohandler.settarget (TAR);


Invohandler.setproxy (Proxy.newproxyinstance (Tar.getclass (). getClassLoader (),


Tar.getclass (). Getinterfaces (), Invohandler));


catch (Exception e) {


E.printstacktrace ();


}


Invohandlers.put (Clazz, Invohandler);

}

Return (T) invohandler.getproxy ();
}

@Override
public object invoke (object proxy, Method method, object[] args) throws Throwable {

Object result = Method.invoke (target, args); Perform business processing

Print Log
Logger.info ("____invoke method:" + method.getname ()
+ "; Args: "+ (null = = args?") Null ": Arrays.aslist (args). toString ())
+ "; return: "+ result";


return result;
}

Public Object Gettarget () {
return target;
}

public void Settarget (Object target) {
This.target = target;
}

Public Object GetProxy () {
return proxy;
}

public void SetProxy (Object proxy) {
This.proxy = proxy;
}
}




And then write a test class testing:

Copy Code code as follows:



/**


* Created with IntelliJ idea.


* Author:wangjie email:tiantian.china.2@gmail.com


* date:13-9-24


* Time: 9:54


*/


public class Test {


public static Logger Logger = Logger.getlogger (Test.class.getSimpleName ());


public static void Main (string[] args) {

Bussinessservice bs = loginvohandler.getproxyinstance (Bussinessserviceimpl.class);
Bs.login ("Zhangsan", "123456");
Bs.find ();

Logger.info ("--------------------------------------");

Workservice ws = Loginvohandler.getproxyinstance (Workserviceimpl.class);
Ws.work ();
Ws.sleep ();

Logger.info ("--------------------------------------");

Bussinessservice BSS = loginvohandler.getproxyinstance (Bussinessserviceimpl.class);
Bss.login ("Lisi", "654321");
Bss.find ();

}
}




You will need to add a new business logic Xxxservice later, just call

Xxxservice xs = loginvohandler.getproxyinstance (xxxserviceimpl.class);

Can.

You can also mimic the configuration of a framework such as spring and configure the Bean's class name in an XML file, such as:

<bean id= "Bussinessservice" class= "Com.wangjie.aoptest2.service.impl.BussinessServiceImpl" >

Then parsing the XML in Java code, by Class.forName ("Com.wangjie.aoptest2.service.impl.BussinessServiceImpl"), and getting the class object

Then through Loginvohandler.getproxyinstance (Class.forName ("Com.wangjie.aoptest2.service.impl.BussinessServiceImpl")); Get proxy object Proxy

Then use reflection to invoke the method of the proxy object.

The results of the operation are as follows:

September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.invohandler.LogInvoHandler invoke


INFO: ____invoke method:login; args: [Zhangsan, 123456]; Return:login success


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.invohandler.LogInvoHandler invoke


INFO: ____invoke method:find; Args:null; Return:find success


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.Test Main


INFO:--------------------------------------


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.invohandler.LogInvoHandler invoke


INFO: ____invoke method:work; Args:null; Return:work success


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.invohandler.LogInvoHandler invoke


INFO: ____invoke method:sleep; Args:null; Return:sleep success


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.Test Main


INFO:--------------------------------------


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.invohandler.LogInvoHandler invoke


INFO: ____invoke method:login; args: [Lisi, 654321]; Return:login success


September 24, 2013 11:08:03 a.m. Com.wangjie.aoptest2.invohandler.LogInvoHandler invoke


INFO: ____invoke method:find; Args:null; Return:find success

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.