接下来学习有关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)