程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Spring實現代理機制

Spring實現代理機制

編輯:關於JAVA

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved