Spring——APO(待完)


导入依赖包

 <dependency>
     <groupId>org.aspectjgroupId>
     <artifactId>aspectjweaverartifactId>
     <version>1.9.6version>
 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"/>
 ?
     
     
     <aop:config>
         
         
         <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>
     
     <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/>