Spring——APO(待完)

导入依赖包

 <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.9.6</version>
 </dependency>

方式一:使用Spring的API接口(接口实现:MethodBeforeAdvice、AfterReturningAdvice)

 <?xml version="1.0" encoding="GBK"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/aop
          https://www.springframework.org/schema/aop/spring-aop.xsd">
 
     <bean id="userService" class="com.yl.service.UserServiceImpl"/>
     <bean id="log" class="com.yl.log.Log"/>
     <bean id="afterLog" class="com.yl.log.AfterLog"/>
 
     <!--方式一:使用原生Spring API接口-->
     <!--配置aop:需要导入aop的约束-->
     <aop:config>
         <!--切入点,expression:表达式,execution(要执行的位置)-->
         <!--第一个*代表可以执行所有的方法类型 第二个*代表实现接口的所有方法 (..)代表所有属性-->
         <aop:pointcut id="pointcut" expression="execution(* com.yl.service.UserServiceImpl.*(..))"/>
         <!--执行环绕增加-->
         <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
         <!--增强哪个类,切入到哪里-->
         <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
     </aop:config>
 
 </beans>

execution(修饰符 返回值 包名.类名/接口名.方法名(参数列表))上面忽略掉修饰符了 (..)可以代表所有参数,( * )代表一个参数,(*,String)代表第一个参数为任何值,第二个参数为String类型

 

方式二:自定义实现(切面定义)

 <!--方式二:自定义类-->
 <bean id="diy" class="com.yl.diy.DiyPointCut"/>
 <aop:config>
     <!--自定义切面,ref要引用的类-->
     <aop:aspect ref="diy">
         <!--切入点-->
         <aop:pointcut id="point" expression="execution(* com.yl.service.UserServiceImpl.*(..))"/>
         <aop:before method="before" pointcut-ref="point"/>
         <aop:after method="after" pointcut-ref="point"/>
     </aop:aspect>
 </aop:config>

 

方式三:注解实现

 //使用注解实现AOP
 @Aspect//标明这个类是一个切面
 public class AnnotationPointCut {
     @Before("execution(* com.yl.service.UserServiceImpl.*(..))")
     public void before(){
         System.out.println("方法执行前");
    }
 
     @After("execution(* com.yl.service.UserServiceImpl.*(..))")
     public void after(){
         System.out.println("方法执行后");
    }
 
     //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
     @Around("execution(* com.yl.service.UserServiceImpl.*(..))")
     public void around(ProceedingJoinPoint joinPoint) throws Throwable {
         System.out.println("环绕前");
 
         //执行方法
         Object proceed = joinPoint.proceed();
 
         System.out.println("环绕后");
    }
 }

顺序:around-before-after-around

xml配置

 <!--方式三-->
 <bean id="annotationPointCut" class="com.yl.diy.AnnotationPointCut"/>
 <!--开启注解支持-->
 <aop:aspectj-autoproxy/>

 

posted @ 2020-09-02 20:44  Fabulo  阅读(215)  评论(0)    收藏  举报