Spring實現代理機制

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.