Spring实现代理机制[Java编程]
本文“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
以上是“Spring实现代理机制[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |