上一笔记,介绍了代理机制,这一节介绍Spring是如何实现代理。
通过一个例子来说明。
包下载地址(两个都要下):
http://www.blogjava.net/Files/ducklyl/springaop.rar
http://www.blogjava.net/Files/ducklyl/Spring.rar
(1)创建LogBeforeAdvice类(实现MethodBeforeAdvice接口,会在目标对象的方法执行之前被中呼叫)package com.proxy;
import java.lang.reflect.*;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.springframework.aop.MethodBeforeAdvice;;
public class LogBeforeAdvice implements MethodBeforeAdvice{
private Logger logger=Logger.getLogger(this.getClass().getName());
public void before(Method method,Object[] args,Object target) throws Throwable
{
logger.log(Level.INFO,"mehtod starts "+method);
}
}
(2)创建配置文件advice-config.xml<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="logBeforeAdvice" class="com.proxy.LogBeforeAdvice" />
<bean id="helloSpeaker" class="com.proxy.HelloSpeaker" />
<bean id="helloProxy"
class="org.springframework.aop.framework.ProxyFactoryBean"><!--建立代理对象-->
<property name="proxyInterfaces"><!--代理接口-->
<value>com.proxy.IHello</value>
</property>
<property name="target"><!--代理目标-->
<ref bean="helloSpeaker" />
</property>
<property name="interceptorNames"><!--代理实现类-->
<list>
<value>logBeforeAdvice</value>
</list>
</property>
</bean>
</beans>
(3)测试类SpringAOPDemo
package com.proxy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringAOPDemo {
public static void main(String[] args)
{
//读取配置文件
ApplicationContext context=new FileSystemXmlApplicationContext("advice-config.xml");
IHello helloProxy=(IHello)context.getBean("helloProxy");
helloProxy.hello("ducklyl");
}
}
运行测试类,结果如下:
Hello,ducklyl