接下來學習有關AOP,首先了解有關代理機制(Spring實現AOP的一種方式)。代理分為兩種:靜態代理與動態代理。
通過一個例子來了解靜態代理。
Lib包下載:
http://www.ziddu.com/download/3555992/SpringAndaop.rar.html
(1)一個簡單的接口IHello
package com.proxy;
/**
* 接口
*
* **/
public interface IHello {
public void hello(String name);
}
(2)實現類HelloSpeaker
package com.proxy;
public class HelloSpeaker implements IHello{
public void hello(String name) {
System.out.println("Hello,"+name);
}
}
(3)代理類HelloProxy
package com.proxy;
import java.util.logging.*;
/**
* 靜態代理類,代理真正的實現類HelloSpeaker來執行
*
* */
public class HelloProxy implements IHello{
private Logger logger=Logger.getLogger(this.getClass().getName());
private IHello helloObject;//接口聲明
//構造函數
public HelloProxy(IHello helloObject)
{
this.helloObject=helloObject;
}
//接口實現方法
public void hello(String name)
{
log("hello methods starts...");
helloObject.hello(name);
log("hello methods ends...");
}
private void log(String msg)
{
logger.log(Level.INFO,msg);
}
}
(4)測試類ProxyDemo
package com.proxy;
public class ProxyDemo {
public static void main(String[] args)
{
//靜態代理模式
HelloProxy proxy=new HelloProxy(new HelloSpeaker());
proxy.hello("ducklyl");
}
}
運行測試類,結果為:
Hello,ducklyl
2007-10-28 10:52:26 com.proxy.HelloProxy log
信息: hello methods starts...
2007-10-28 10:52:27 com.proxy.HelloProxy log
信息: hello methods ends...
接下來介紹動態代理
(1)創建動態代理類LogHandler
package com.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.*;
/**
*
* 動態代理類
* **/
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
public LogHandler()
{
}
public Object bind(Object delegate) {
this.delegate = delegate;
log("bind starts...");
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
delegate.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
log("method starts..." + method);
result = method.invoke(delegate, args);
log("method ends..." + method);
} catch (Exception e) {
log(e.toString());
}
return null;
}
private void log(String msg) {
logger.log(Level.INFO, msg);
}
}
(2)創建測試類ProxyTest
package com.proxy;
public class ProxyTest {
public static void main(String[] args)
{
LogHandler logHandler=new LogHandler();
//logHandler代理HelloSpeaker實例,調用hello
IHello helloProxy=(IHello)logHandler.bind(new HelloSpeaker());
helloProxy.hello("ducklyl");
}
}
運行測試類,結果為:
Hello,ducklyl
2007-10-28 11:24:59 com.proxy.LogHandler log
信息: bind starts...
2007-10-28 11:24:59 com.proxy.LogHandler log
信息: method starts...public abstract void com.proxy.IHello.hello(java.lang.String)
2007-10-28 11:24:59 com.proxy.LogHandler log
信息: method ends...public abstract void com.proxy.IHello.hello(java.lang.String)