AOP快速入门案例(四)

来源:互联网 发布:js实现三级下拉菜单 编辑:程序博客网 时间:2024/05/22 06:56
一 引用通知
以前定义的通知类型是在目标对象的方法被调用的周围织入。引入通知给目标对象添加新的方法和属性。

二 配置方法
<?xml version="1.0" encoding="utf-8"?><beans xmlns="http://www.springframework.org/schema/beans";                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";                xmlns:context="http://www.springframework.org/schema/context";                xmlns:tx="http://www.springframework.org/schema/tx";                xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";                                ><!-- 配置被代理的对象 --><bean id="test1Service" class="com.hsp.aop.Test1Service"><property name="name" value="顺平" /></bean><!-- 配置前置通知        proxyFactoryBean implements TestServiceInter,TestServiceInter2{                public void sayHello();        }                思考        interface Inter1{};        class A implements Inter1,Inter2{        }        Inter1 a=new A();        Inter2 b=(Inter2)a;--><bean id="MyMethodBeforeAdvice" class="com.hsp.aop.MyMethodBeforeAdvice" /><bean id="myAfterReturningAdvice" class="com.hsp.aop.MyAfterReturningAdvice" /><bean id="myMethodInterceptor" class="com.hsp.aop.MyMethodInterceptor" /><bean id="myThrowsAdvice" class="com.hsp.aop.MyThrowsAdvice "/><bean id="myMethodBeforeAdvieFilter" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">        <property name="advice" ref="MyMethodBeforeAdvice"></property>        <property name="mappedNames">                <list>                <value>sayHello</value>                </list>        </property></bean><!-- 配置代理对象 --><bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean"><!-- 代理接口集 --><property name="proxyInterfaces">        <list>                <value>com.hsp.aop.TestServiceInter</value>                <value>com.hsp.aop.TestServiceInter2</value>        </list></property><!-- 把通知织入到代理对象  --><property name="interceptorNames">        <!-- 相当于包MyMethodBeforeAdvice前置通知和代理对象关联,我们也        可以把通知看出拦截器,struts2核心拦截器 -->        <list>                <value>myMethodBeforeAdvieFilter</value>                <value>myAfterReturningAdvice</value>                <value>myMethodInterceptor</value>                <value>myThrowsAdvice</value>        </list></property><!-- 配置被代理对象,可以指定 --><property name="target" ref="test1Service"/></bean></beans>

三 运行结果
记录日志...sayHello
调用方法前
hi 顺平
调用方法后
关闭资源...
调用方法前
bye 顺平
调用方法后
关闭资源...

四 FAQ
1 当你通过代理对象去实现aop的时候,获取的ProxyFactoryBean是什么类型?
答: 返回的是一个代理对象,如果目标对象实现了接口,则spring使用jdk 动态代理技术,如果目标对象没有实现接口,则spring使用CGLIB技术。

五 正则表达式切入点RegexpMethodPointcut
原创粉丝点击