(六) 拦截器配置
把三个拦截器连同Service实现类配置到Spring中。Spring将实例化3个拦截器对象,一个Service对象,并安装指定的规则装配。
实际上,Spring无法将Service实现类与拦截器类直接组装,因为没有对应的getter,setter方法。安装时借助的是Spring的代理类,即把拦截器安装到NameMatchPointcutAdvisor中,把自定义的Service安装到了ProxyFactoryBean中,然后组装在一块。配置代码如下:
<!-- 拦截器 在withAop()方法前进行 安装到NameMatchPointcutAdvisor中 -->
<bean id="aopMethodBeforeInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.zhangjie.spring.aop.MethodBeforeInterceptor"></bean>
</property>
<property name="mappedName" value="withAop"></property>
</bean>
<!-- 拦截器 在withAop()返回后运行 安装到NameMethodMethodPointcutAdvisor中 -->
<bean id="aopMethodAfterInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.zhangjie.spring.aop.MethodAfterInterceptor"></bean>
</property>
<property name="mappedName" value="withAop"></property>
</bean>
<!-- 拦截器 在异常抛出后运行 安装到NameMatchMethodPointcutAdvisor中 -->
<bean id="aopThrowsInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.zhangjie.spring.aop.ThrowsInterceptor"></bean>
</property>
<property name="mappedName" value="withAop"></property>
</bean>
<!-- Service对象,安装到ProxyFactoryBean对象中 -->
<bean id="aopService" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 拦截器 -->
<property name="interceptorNames">
<list>
<value>aopMethodBeforeInterceptor</value>
<value>aopMethodAfterInterceptor</value>
<value>aopThrowsInterceptor</value>
</list>
</property>
<property name="target">
<bean class="com.zhangjie.spring.aop.AopServiceImpl">
<property name="name" value="zhangjie"></property>
</bean>
</property>
</bean>
(七) 运行代码
运行代码从Spring容器中获取Service对象,并分别执行Service的两个方法withAop()与withoutAop()。Spring将会在withAop()方法前后添加拦截器,但withoutAop()方法前后则不会添加,代码如下:
package com.zhangjie.spring.aop;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class AopRun {
public static void main(String[] args) throws Exception {
XmlBeanFactory factory = new XmlBeanFactory(
new ClassPathResource("applicationContext.xml")
); //获取Factory
IAopService hello = (IAopService)factory.getBean("aopService");//查找对象
hello.withAop(); //执行withAop()
hello.withoutAop();//指定withoutAop()
factory.destroySingletons();// 销毁对象
}
}
(八) 运行效果