通過一個(gè)例子來說明。
包下載地址:
http://www.ziddu.com/download/3555992/SpringAndaop.rar.html
(1)創(chuàng)建LogBeforeAdvice類(實(shí)現(xiàn)MethodBeforeAdvice接口,會(huì)在目標(biāo)對象的方法執(zhí)行之前被呼叫)
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)創(chuàng)建配置文件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"><!--代理目標(biāo)-->
<ref bean="helloSpeaker" />
</property>
<property name="interceptorNames"><!--代理實(shí)現(xiàn)類-->
<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");
}
}
運(yùn)行測試類,結(jié)果如下:
Hello,ducklyl