Spring-AOP 引介切面

来源:互联网 发布:python的idle怎么运行 编辑:程序博客网 时间:2024/05/18 00:16

  • 概述
    • 引介切面类继承关系
    • IntroductionAdvisor接口的两个实现类
    • DefaultIntroductionAdvisor的构造函数
  • 实例

概述

之前的博文介绍了 Spring-AOP 通过配置文件实现 引介增强 ,引介切面是引介增强的封装器,通过引介切面可以很容易的为现有对象添加任何接口的实现。

引介切面类继承关系

这里写图片描述

IntroductionAdvisor 和 PointcutAdvisor不同,IntroductionAdvisor 仅有一个类过滤器ClassFilter而没有MethodMatcher,因为引介切面是类级别的,而Poincut的切点是方法级别的。

IntroductionAdvisor接口的两个实现类

这里写图片描述

  • DefaultIntroductionAdvisor
    引介切面最常用的实现类

  • DeclareParentsAdvisor
    用于实现使用AspectJ语言的DeclareParent注解表示的引介切面。

DefaultIntroductionAdvisor的构造函数

这里写图片描述

  • public DefaultIntroductionAdvisor(Advice advice)

    通过一个增强创建的引介切面,引介切面将为目标对象增强对象中所有接口的实现

  • public DefaultIntroductionAdvisor(Advice advice, IntroductionInfo
    introductionInfo)
    通过一个增强和一个IntroductionInfo创建引介切面,目标对象小实现哪些接口由introduction对象的getInterfaces()方法标识

  • public DefaultIntroductionAdvisor(DynamicIntroductionAdvice advice,
    Class<?> intf)
    通过一个IE增强和一个指定的接口类创建引介切面,仅为目标对象新增intf接口的实现


实例

代码已托管到Github—> https://github.com/yangshangwei/SpringMaster

这里写图片描述

其余代码同 Spring-AOP 通过配置文件实现 引介增强

我们通过DefaultIntroductionAdvisor配置引介切面,更加简洁、清晰

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <!-- 目标类 -->    <bean id="forumServiceTarget" class="com.xgj.aop.spring.advisor.introductionAdvisor.ForumService" />    <!-- 切面 -->    <bean id="introductionAdvisor" class="org.springframework.aop.support.DefaultIntroductionAdvisor">        <constructor-arg>            <bean class="com.xgj.aop.spring.advisor.introductionAdvisor.ControllablePerformaceMonitor"/>        </constructor-arg>    </bean>    <!-- 代理类  -->    <bean id="forumService" class="org.springframework.aop.framework.ProxyFactoryBean"        p:interceptorNames="introductionAdvisor"        p:target-ref="forumServiceTarget"         p:proxyTargetClass="true" /></beans>

运行结果:

2017-08-20 19:02:30,492  INFO [main] (AbstractApplicationContext.java:583) - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5f0101fb: startup date [Sun Aug 20 19:02:30 BOT 2017]; root of context hierarchy2017-08-20 19:02:30,598  INFO [main] (XmlBeanDefinitionReader.java:317) - Loading XML bean definitions from class path resource [com/xgj/aop/spring/advisor/introductionAdvisor/conf-introductionAdvisor.xml]模拟删除Forum记录:10模拟删除Topic记录:1022begin monitor...模拟删除Forum记录:10end monitor...org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.removeForum花费7421毫秒。begin monitor...模拟删除Topic记录:1022end monitor...org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.removeTopic花费12468毫秒。

虽然引介切面和其他切面的配置有很大的不同,但却可以采用相似的Spring配置方式配置引介切面。

原创粉丝点击