上一筆記,介紹了代理機制,這一節介紹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