Spring AOP 常用的四种实现方式

1.  AOP的相关术语

1.通知(Advice): 
          通知定义了切面是什么以及何时使用。描述了切面要完成的工作和何时需要执行这个工作。 
2.连接点(Joinpoint): 
         程序能够应用通知的一个“时机”,这些“时机”就是连接点,例如方法被调用时、异常被抛出时等等。 
3.切入点(Pointcut) 
        通知定义了切面要发生的“故事”和时间,那么切入点就定义了“故事”发生的地点,例如某个类或方法的名称,Spring中允许我们方便的用正则表达式来指定 
4.切面(Aspect) 
        通知和切入点共同组成了切面:时间、地点和要发生的“故事” 
5.引入(Introduction) 
        引入允许我们向现有的类添加新的方法和属性(Spring提供了一个方法注入的功能) 
6.目标(Target) 
        即被通知的对象,如果没有AOP,那么它的逻辑将要交叉别的事务逻辑,有了AOP之后它可以只关注自己要做的事(AOP让他做爱做的事) 
7.代理(proxy) 
        应用通知的对象,详细内容参见设计模式里面的代理模式 
8.织入(Weaving) 
  把切面应用到目标对象来创建新的代理对象的过程,织入一般发生在如下几个时机
        (1)编译时:当一个类文件被编译时进行织入,这需要特殊的编译器才可以做的到,例如AspectJ的织入编译器 
        (2)类加载时:使用特殊的ClassLoader在目标类被加载到程序之前增强类的字节代码 
        (3)运行时:切面在运行的某个时刻被织入,SpringAOP就是以这种方式织入切面的,原理应该是使用了JDK的动态代理技术


2. Spring支持五种类型的通知 
Before()  org.apringframework.aop.MethodBeforeAdvice 
After-returning(返回后) org.springframework.aop.AfterReturningAdvice 
After-throwing(抛出后) org.springframework.aop.ThrowsAdvice 
Arround(周围) org.aopaliance.intercept.MethodInterceptor 
Introduction(引入) org.springframework.aop.IntroductionInterceptor 

周围通知是由AOP Alliance中的接口定义的而非Spring,周围通知相当于前通知、返回后通知、抛出后通知的结合


3.实例

写一个接口叫Sleepable

package test.spring.aop.bean   

 public interface Sleepable{   

    void sleep();    

 } 

然后写一个Human类,实现了这个接口 

package test.spring.aop.bean   

public Human implements Sleepable{   

   public void sleep(){   

      System.out.println("睡觉了!梦中自有颜如玉!");   

   }   
}  

不过睡觉前后要做些辅助工作,但是这些辅助工作与纯粹的睡觉这一“业务逻辑”是不相干的,如果把 这些代码全部加入到sleep方法中,是不是有违单一职责呢?,这时候就需要AOP了。 
编写一个SleepHelper类,它里面包含了睡觉的辅助工作,AOP术语来说它就应该是通知了。需要实现上面的接口 

package test.spring.aop.bean;   
import java.lang.reflect.Method;   
import org.springframework.aop.AfterReturningAdvice;   
import org.springframework.aop.MethodBeforeAdvice;   

public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{   

    public void before(Method mtd, Object[] arg1, Object arg2) throws Throwable {   

            System.out.println("通常情况下睡觉之前要脱衣服!");   

     }   

    public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {   

        System.out.println("起床后要先穿衣服!");   

    }   

}  

然后在spring配置文件中进行配置:

<bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">  
</bean>  

Spring使用org.springframework.aop.support.JdkRegexpMethodPointcut来定义正则表达式切点 

<bean id="spleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">  

      <property name="pattern" value=".*sleep"/>  

</bean>  

pattern属性指定了正则表达式,它匹配所有的sleep方法 
切点仅仅是定义了故事发生的地点,还有故事发生的时间以及最重要的故事的内容,就是通知了,我们需要把通知跟切点结合起来,我们要使用的通知者是org.springframework.aop.support.DefaultPointcutAdvisor   

<bean id="sleepHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">   

     <property name="advice" ref="sleepHelper"/>   

     <property name="pointcut" ref="sleepPointcut"/>   

</bean>  

切入点和通知都配置完成,接下来该调用ProxyFactoryBean产生代理对象了

<bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  

     <property name="target" ref="human"/>  

     <property name="interceptorNames" value="sleepHelperAdvisor" />  

     <property name="proxyInterfaces" value="test.spring.aop.bean.Sleepable" />  

</bean>  

ProxyFactoryBean是一个代理,我们可以把它转换为proxyInterfaces中指定的实现该interface的代理对象

import org.springframework.aop.framework.ProxyFactoryBean;   
import org.springframework.context.ApplicationContext;   
import org.springframework.context.support.ClassPathXmlApplicationContext;   
import test.spring.aop.bean.Sleepable;   

public class Test {   

    public static void main(String[] args){   

        ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");   

        Sleepable sleeper = (Sleepable)appCtx.getBean("humanProxy");   

        sleeper.sleep();   

    }   

}  

程序运行产生结果: 

通常情况下睡觉之前要脱衣服! 
睡觉啦~梦中自有颜如玉! 
起床后要先穿衣服! 

Spring提供了一种自动代理的功能,能让切点跟通知自动进行匹配,修改配置文件如下: 

<bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">  

 </bean>  

<bean id="sleepAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  

   <property name="advice" ref="sleepHelper"/>  

   <property name="pattern" value=".*sleep"/>  

 </bean>  

 <bean id="human" class="test.spring.aop.bean.Human">  

 </bean>  

 <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>  

执行程序: 

public class Test {   

    public static void main(String[] args){   

        ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");   

        Sleepable sleeper = (Sleepable)appCtx.getBean("human");   

        sleeper.sleep();   

    }   

}  


4. 使用AspectJ提供的注解:

Java代码 

package test.mine.spring.bean;   

import org.aspectj.lang.annotation.AfterReturning;   
import org.aspectj.lang.annotation.Aspect;   
import org.aspectj.lang.annotation.Before;   
import org.aspectj.lang.annotation.Pointcut;   

@Aspect  
public class SleepHelper {   

    public SleepHelper(){         

    }   
    
    @Pointcut("execution(* *.sleep())")   
    public void sleeppoint(){}   


    @Before("sleeppoint()")   
    public void beforeSleep(){   

        System.out.println("睡觉前要脱衣服!");   

    }   

      
    @AfterReturning("sleeppoint()")   
    public void afterSleep(){   

        System.out.println("睡醒了要穿衣服!");   

    }   

}  


@Aspect的注解来标识切面,注意不要把它漏了,否则Spring创建代理的时候会找不到它,@Pointcut注解指定了切点,@Before@AfterReturning指定了运行时的通知,注意的是要在注解中传入切点的名称 .然后在Spring配置文件上增加AOPXML命名空间和声明相关schema 命名空间xmlns:aop="http://www.springframework.org/schema/aop" 

schema声明

http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 
然后加上这个标签<aop:aspectj-autoproxy/> 有了这个Spring就能够自动扫描被@Aspect标注的切面了 .

public class Test {   

    public static void main(String[] args){   

        ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");   

        Sleepable human = (Sleepable)appCtx.getBean("human");   

        human.sleep();   

    }   
}  

下面来看最后一种常用的实现AOP的方式:使用Spring来定义纯粹的POJO切面前面我们用到了<aop:aspectj-autoproxy/>标签,Springaop的命名空间里面还提供了其他的配置元素

<aop:advisor> 定义一个AOP通知者 ,

<aop:after> 后通知 ,

<aop:after-returning> 返回后通知 

<aop:after-throwing> 抛出后通知 ,

<aop:around> 周围通知 ,

<aop:aspect>定义一个切面 

<aop:before>前通知 ,

<aop:config>顶级配置元素,类似于<beans>这种东西 ,

<aop:pointcut>定义一个切点 .

AOP标签来实现睡觉这个过程
代码不变,只是修改配置文件,加入AOP配置即可

<aop:config>  

    <aop:aspect ref="sleepHelper">  

        <aop:before method="beforeSleep" pointcut="execution(* *.sleep(..))"/>  

        <aop:after method="afterSleep" pointcut="execution(* *.sleep(..))"/>  

    </aop:aspect>  

</aop:config>  


5.

通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了<aop:aspectj-autoproxy />有一个proxy-target-class属性,

默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。


6 .  切入点表达式 @Pointcut("execution(* com.cjm.model..*.*(..))")  

1、切入点表达式的格式:execution([可见性] 返回类型 [声明类型].方法名(参数) [异常])

2、切入点表达式通配符:
      *:匹配所有字符
      ..:一般用于匹配多个包,多个参数
      +:表示类及其子类

3、切入点表达式支持逻辑运算符:&&||!

4、切入点表达式关键词:
      1execution用于匹配子表达式。

      //匹配com.cjm.model包及其子包中所有类中的所有方法,返回类型任意,方法参数任意
        @Pointcut("execution(* com.cjm.model..*.*(..))")
        public void before(){}

      2within用于匹配连接点所在的Java类或者包。

     //匹配Person类中的所有方法
     @Pointcut("within(com.cjm.model.Person)")
      public void before(){}

     //匹配com.cjm包及其子包中所有类中的所有方法
      @Pointcut("within(com.cjm..*)")
      public void before(){}

     3this用于向通知方法中传入代理对象的引用。

      @Before("before() && this(proxy)")
      public void beforeAdvide(JoinPoint point, Object proxy){
                  //处理逻辑
       }

      4target用于向通知方法中传入目标对象的引用。

    @Before("before() && target(target)
    public void beforeAdvide(JoinPoint point, Object proxy){
                  //处理逻辑
     }

      5args用于将参数传入到通知方法中。      

   @Before("before() && args(age,username)")
    public void beforeAdvide(JoinPoint point, int age, String username){
                  //处理逻辑
      }
       6@within 用于匹配在类一级使用了参数确定的注解的类,其所有方法都将被匹配。 
 @Pointcut("@within(com.cjm.annotation.AdviceAnnotation)")

 所有被@AdviceAnnotation标注的类都将匹配

public void before(){}

@Retention(RetentionPolicy.RUNTIME)  
@Target({ElementType.TYPE, ElementType.METHOD})  
@Documented  
@Inherited  
public @interface AdviceAnnotation {  

}  

  7@target@within的功能类似,但必须要指定注解接口的保留策略为RUNTIME

    @Pointcut("@target(com.cjm.annotation.AdviceAnnotation)")
    public void before(){}

 8@args传入连接点的对象对应的Java类必须被@args指定的Annotation注解标注。

   @Before("@args(com.cjm.annotation.AdviceAnnotation)")
    public void beforeAdvide(JoinPoint point){
                  //处理逻辑
     }
public class Person {  

    public void say(Address address){  
          //处理逻辑  
   } 
}  

  
 @AdviceAnnotation  
 public class Address {  
     
 }  

如果需要在Person类的say方法被调用时触发beforeAdvide通知,那么say方法的参数对应的Java类型Address类必须要被@AdviceAnnotation标注。

 9@annotation匹配连接点被它参数指定的Annotation注解的方法。也就是说,所有被指定注解标注的方法都将匹配。       

   @Pointcut("@annotation(com.cjm.annotation.AdviceAnnotation)")
   public void before(){}
public class Person {  

      @AdviceAnnotation  
      public void say(Address address){  
              //处理逻辑  
    }  
}  

 Person类的say方法被@AdviceAnnotation标注,所以它匹配。

  10bean通过受管Bean的名字来限定连接点所在的Bean。该关键词是Spring2.5新增的。

    @Pointcut("bean(person)")
    public void before(){}

idperson的受管Bean中的所有方法都将匹配。

            @Pointcut("@within(com.cjm.annotation.AdviceAnnotation)")
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值