AOP基础

一.AOP基本概念

AOP可以是核心业务与周边功能相分离,将那些与核心业务无关,但是被所有核心业务所共同调用的周边功能进行了分装,以减少系统代码的重复,降低模块之间的耦合度,并有利于未来的可拓展性与维护性。


image.png
面(Aspect):横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象
通知(Avee):切面必须要完成的工作
目标(Target):被通知的对象
代理(Proxy):向目标对象应用通知之后创建的对象
连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点相对点表示的方位。例如 ArithmethicCalculator#addO方法执行前的连接点,执行点为 ArithmethicCalculator#adcO;方位为该方法执行前的位匱
切点(Pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org。 springframework aop, Pointcut接口进行描述,它使用类和方法作为连接点的查询条件。

切面:周边功能在Spring的面向切面编程AOP思想当中即被定义为切面

那什么是面向切编程呢?在面向切面编程AOP的思想当中,核心业务与周边功能分别独立开发,然后把核心业务与切面"编织"在一起,这就叫AOP,这是为了减少系统代码的重复,降低耦合度。
AOP的实现方式:
预编译
动态代理
AOP是采用横向抽取的机制,即代理的机制,Spring的传统的AOP底层有2种代理机制,即:JDK的动态代理(JDK本身的)和第三方的CGLIB代理机制(第三方的)

(1)JDK动态代理(只能对实现了接口的类进行代理)

package com.imooc.aop.demo1;

public interface UserDao {

    public void save();

    public void update();

    public void delete();

    public void find();
}
************************************************************
package com.imooc.aop.demo1;

public class UserDaoImpl implements UserDao {

    @Override
    public void save() {

        System.out.println("保存。。。");
    }

    @Override
    public void update() {

        System.out.println("修改。。。");

    }

    @Override
    public void delete() {

        System.out.println("删除。。。");

    }

    @Override
    public void find() {

        System.out.println("查找。。。");
    }
}
************************************************************
package com.imooc.aop.demo1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 要实现代理,我们要首选JDK的动态代理,JDK的动态代理要实现
 */
public class MyJDKProxy implements InvocationHandler {

    private UserDao userDao;

    public MyJDKProxy(UserDao userDao){

       this.userDao=userDao;
    }


    public Object createProxy(){

        /**
         * 第一个参数是类的加载器
         * 第二个参数是接口
         * 第三个参数是我们要的代理类
         */
        Object proxy=Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(),this);
        return proxy;
    }

    /**
     * invoke方法是我们真正要的哪个方法
     * 调用UserDao当中的添加删除操作都是调用invoke方法
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("save".equals(method.getName())){

            System.out.println("权限校验.........");
            return method.invoke(userDao,args);
        }

        return method.invoke(userDao,args);
    }
}
************************************************************
package com.imooc.aop.demo1;

import org.junit.jupiter.api.Test;

public class SpringTest {

    @Test
    public void test(){

        UserDao userDao=new UserDaoImpl();

        UserDao proxy=(UserDao) new MyJDKProxy(userDao).createProxy();

        proxy.save();

        proxy.delete();

        proxy.find();

        proxy.update();

    }
}

(2)CGLIB代理(没有实现接口也可以代理)

package com.imooc.aop.demo2;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyCglibProxy implements MethodInterceptor {

    private ProductDao productDao;

    public MyCglibProxy(ProductDao productDao){

        this.productDao=productDao;
    }

    /**
     * 编写一个方法去创建代理类
     */
    public Object createProxy(){

        //1.创建核心类
        Enhancer enhancer=new Enhancer();

        //2.设置父类(对目标类产生一个子类)
        enhancer.setSuperclass(productDao.getClass());

        //3.设置回调
        enhancer.setCallback(this);

        //4.生成代理
        Object proxy=enhancer.create();

        return proxy;

    }

    /**
     * 有点类似于invoke
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        if("save".equals(method.getName())){

            System.out.println("进行权限校验...");

            return  methodProxy.invokeSuper(proxy,objects);
        }
        return methodProxy.invokeSuper(proxy,objects);
    }

}
****************************************************************************
package com.imooc.aop.demo2;

import org.junit.jupiter.api.Test;

public class SpringTest1 {

    @Test
    public void test(){

        ProductDao productDao=new ProductDao();

//        productDao.delete();
//        productDao.find();
//        productDao.update();
//        productDao.save();

        ProductDao proxy=(ProductDao) new MyCglibProxy(productDao).createProxy();

        proxy.save();

    }

}

Spring在运行期生成动态代理,不需要特殊的编译器
Spring AOP的底层就是通过JDK动态代理或者CGLIB动态代理技术为目标Bean执行横向织入:
1.若目标对象实现了若干的接口,Spring使用的是JDK的java.lang.reflect.Proxy类代理
2.若目标对象没有实现任何的接口,Spring使用CGLIB库生成目标对象的子类

(3)基于bean名称的自动代理方式

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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="studentDao" class="com.imooc.aop.demo5.StudentDaoImpl"/>
    <bean id="customerDao" class="com.imooc.aop.demo5.CustomerDao"/>


    <!--配置增强/通知-->
    <bean id="myBeforeAdvice" class="com.imooc.aop.demo5.MyBeforeAdvice"/>
    <bean id="myAroundAdvice" class="com.imooc.aop.demo5.MyAroundAdvice"/>


    <!--配置自动代理:基于bean名称的自动代理方式-->
    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames" value="*Dao"/>
        <property name="interceptorNames" value="myBeforeAdvice"/>
    </bean>
</beans>
=====================================================
package com.imooc.aop.demo6;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean4.xml")
public class SpringTest {

    @Resource(name="studentDao")
    private StudentDao studentDao;

    @Resource(name="customerDao")
    private CustomerDao customerDao;

    @Test
    public void test(){

        studentDao.save();
        studentDao.delete();
        studentDao.find();
        studentDao.update();
        System.out.println("=============================================");
        customerDao.delete();
        customerDao.find();
        customerDao.save();
        customerDao.update();
    }
}

(4)基于切面信息的自动代理方式

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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="studentDao" class="com.imooc.aop.demo6.StudentDaoImpl"/>
    <bean id="customerDao" class="com.imooc.aop.demo6.CustomerDao"/>


    <!--配置增强/通知-->
    <bean id="myBeforeAdvice" class="com.imooc.aop.demo6.MyBeforeAdvice"/>
    <bean id="myAroundAdvice" class="com.imooc.aop.demo6.MyAroundAdvice"/>

    <!--配置切面-->
    <bean id="myAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <property name="pattern"  value="com\.imooc\.aop\.demo6\.CustomerDao\.save"/>
        <property name="advice" ref="myAroundAdvice"/>
    </bean>

    <!--配置自动代理:基于切面信息的自动代理方式-->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

</beans>
=======================================================
package com.imooc.aop.demo6;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean4.xml")
public class SpringTest {

    @Resource(name="studentDao")
    private StudentDao studentDao;

    @Resource(name="customerDao")
    private CustomerDao customerDao;

    @Test
    public void test(){

        studentDao.save();
        studentDao.delete();
        studentDao.find();
        studentDao.update();
        System.out.println("=============================================");
        customerDao.delete();
        customerDao.find();
        customerDao.save();
        customerDao.update();
    }
}

二.Spring当中使用AOP(注解的方式)

AspectJ

AspectJ是一个基于java语言的AOP框架,spring2.0以后新增加了对AspectJ切点表达式的支持,@AspectJ是AspectJ1.5新增的功能,通过JDK5注解技术,允许直接在bean类当中定义切面,新版本的Spring框架都建议使用AspectJ的方式来开发AOP

要在 Spring中声明 AspectJ切面,只需要在IOC容器中捋切面声明为Bean实例,当在 Spring lOC容器中初始化 AspectJ切面之后, Spring IOC容器就会为那些与AspectJ切面相匹配的Bean创建代理,
在AspectJ注解中切面只是一个带有@ Aspec注解的Java类
通知是标注有某种注解的简单的Java方法
    Aspect支持5种类型的通知注解:
    @Bepe前匿通知在方法执行之前执行
    @Afe后匿通知在方法执行之后执行
    @AfterRunning返回通知在方法返回结果之后执行
    @After Throwing异常通知在方法抛出异常之后
    @Around环绕通知,围绕着方法执行

首先创建一个类,使用@Aspect来注解,让这个类成为一个切面,在切面当中配置切点(切点当中要配置的是execution方法,来用来说明要横切的类与方法有那些,即:切点的作用是指出那些类与方法需要横切,当前置或者后置通知的时候,需要横切的方法或者类要进行操作),前置通知,前置通知当中的值采用切面

1.引入jar包
2.在配置文件当中加入aop命名空间,基于注解的方式配置加入扫描 
       <context:component-scan base-package="com.mmall" annotation-config="true"/>
       <context:annotation-config/><!--自动为匹配的类生成代理对象-->
3.把横切关注点的代码抽取到切面的类当中
    切面首先是一个IOC容器当中的bean,即加入@Controller注解或其他几个注解
    切面要区别于其他普通的bean,还需要加入@Aspect注解
4.在切面当中申明各种通知
    申明一个方法
    在方法上面添加@Before注解
5.可以在通知方法当中申明一个参数类型为JointPoint的参数,然后就可以访问链接细节,如方法名称和参数
@Aspect
@Controller
public class LoggingAspectJ {

    @Before("execution(* com.mmall.common.* .*(int,int))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName=joinPoint.getSignature().getName();
        List<Object> args= Arrays.asList(joinPoint.getArgs());
        System.out.println("The method "+ methodName+","+"The args"+args);
    }
}
package com.spring.aspect;

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

/**
 * 创建一个类,加入@Aspect注解
 * @author laochaochunfengting
 *
 */
@Aspect
public class PermAspect {
    
    /**
     * 第一个*表示拦截方法的返回值
     * com.spring.userservice包
     * 第一个..表示com.spring.userservice包的子包
     * 第二个*表示所有的方法
     * 第三个*表示所有的方法
     * 第二个..表表示所有的参数
     * 
     * ========================================
     * 可以拦截com.spring.userservice包及子包下的任何类的任何方法,参数任意,返回值任意
     */
    @Pointcut("execution(* com.spring.userservice..*.*(..))")
    public void anyMethod() {
        
    }
    
    /**
     * 在前置通知当中要指定切点
     */
    @Before("anyMethod")
    public void preAdive() {
        
        System.out.println("前置通知!!!!");
    }
    

}

(一)AOP切面设置

package com.spring.aop.impl;

import org.springframework.stereotype.Component;

@Component
public class AtithmeticCalculatorLoggingImpl implements AtithmeticCalculator{

    @Override
    public int add(int i, int j) {
        // TODO Auto-generated method stub
        
        int result=i+j;

        return result;
    }

    @Override
    public int sub(int i, int j) {
        // TODO Auto-generated method stub

        int result=i-j;

        return result;
    }

    @Override
    public int mul(int i, int j) {
        // TODO Auto-generated method stub

        int result=i*j;

        return result;
    }

    @Override
    public int div(int i, int j) {

        int result=i/j;

        return result;
    }

}
***********************************************************************
package com.spring.aop.impl;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//把这个类申明为一个切面:需要把该类放入到IOC容器当中,再申明为一个切面
@Component
@Aspect
public class LoggingAspect {
    
    //申明该方法是一个前置通知
    @Before("execution(public int com.spring.aop.impl.AtithmeticCalculatorLoggingImpl.*(int, int))")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName=joinPoint.getSignature().getName();
        List<Object> args=Arrays.asList(joinPoint.getArgs());
        System.out.println("The method"+methodName+" begins"+args);
    }

}
**********************************************************************************
<?xml version="1.0" encoding="UTF-8"?>
<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

    
    <context:component-scan base-package="com.spring.aop.impl"></context:component-scan>

    <!-- 使AspectJ注解起作用:自动为匹配到的类生成代理对象 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
***************************************************************************
package com.spring.aop.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        
        //创建Spring的IOC容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        
        AtithmeticCalculator acl=ctx.getBean(AtithmeticCalculator.class);
        
        int result=acl.add(2, 5);
        System.out.println(result);
        result=acl.sub(2, 5);
        System.out.println(result);
        
    }

}

package com.spring.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 写一个日志切面
 * @author laochaochunfengting
 *
 */
@Component
@Aspect
public class LoggingAspect {

    /**
     * 要求com.spring.aop.ArithmeticCalculator接口的每一个实现类的每一个方法在执行之前都执行一段代码
     * 如果需要连接细节,则可以防疫个连接点的参数
     */
    @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        /**
         * 获得连接的方法
         */
        String joinMethod=joinPoint.getSignature().getName();
        //获得连接参数
        Object [] args=joinPoint.getArgs();
        
        System.out.println("The Method "+joinMethod+ "  begins with..."+Arrays.asList(args));
        
    }
    /**
     * 后置通知
     * 在方法执行之后执行(无论该方法是否出现异常)
     */
    @After("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public void AfterMethod(JoinPoint joinPoint) {
        /**
         * 获得连接的方法
         */
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  ends ");

    }
    
    /**
     * 返回通知
     * 在方法正常结束之后返回的通知,r如出现异常,不会有返回
     * 返回通知是可以得到方法得到返回值的(调用方法的返回值)
     */
    @AfterReturning(value="execution(public int com.spring.aop.ArithmeticCalculator.*(..))",returning="result")
    public void afterReturn(JoinPoint joinPoint,Object result) {
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  ends with "+result);

    }
    
********可以看出环绕通知的功能十分强大,可以一次加多种通知***********
package com.spring.aop;


import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 写一个日志切面
 * @author laochaochunfengting
 *
 */
@Component
@Aspect
public class LoggingAspectArround {

    /**
     * 环绕通知(必须要传一个参数ProceedingJoinPoint)
     * 环绕通知类似于动态代理的全过程
     * ProceedingJoinPoint类型的参数可以决定知否执行目标方法,
     * 且环绕通知必须有返回值,返回值即为目标方法的返回值
     */
    @Around("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public Object arroundMethod(ProceedingJoinPoint pjp) {
        Object result=null;
        String methodName=pjp.getSignature().getName();
        //执行目标方法 
        try {
            //前置通知
            System.out.println("The Method1 "+methodName+" begins with"+Arrays.asList(pjp.getArgs()));
            result=pjp.proceed();
            //后置通知+返回通知
            System.out.println("The Method1 "+methodName+" ends with"+result);
        } catch (Throwable e) {
            // 异常通知
            System.out.println("The Method1  "+methodName+ "  occurs excetion:with "+e);
        }
        //后置通知
        System.out.println("The Method1 "+methodName+" ends with");
        return result;
    }
}

(二)切面的优先级

可以使用Order来指定切面的优先级,值越小优先级越高

package com.spring.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * 可以使用Order来指定切面的优先级,值越小优先级越高
 * 
 * @author laochaochunfengting
 *
 */
@Order(1)
@Aspect
@Component
public class VidationAspect {

    @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public void validateArgs(JoinPoint joinPoint) {
        
        System.out.println("validate:"+Arrays.asList(joinPoint.getArgs()));
    }
}
************************************************************************************
package com.spring.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 写一个日志切面
 * @author laochaochunfengting
 *
 */
@Order(2)
@Component
@Aspect
public class LoggingAspect {

    /**
     * 要求com.spring.aop.ArithmeticCalculator接口的每一个实现类的每一个方法在执行之前都执行一段代码
     * 如果需要连接细节,则可以防疫个连接点的参数
     */
    @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        /**
         * 获得连接的方法
         */
        String joinMethod=joinPoint.getSignature().getName();
        //获得连接参数
        Object [] args=joinPoint.getArgs();
        
        System.out.println("The Method "+joinMethod+ "  begins with..."+Arrays.asList(args));
        
    }
    /**
     * 后置通知
     * 在方法执行之后执行(无论该方法是否出现异常)
     */
    @After("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public void AfterMethod(JoinPoint joinPoint) {
        /**
         * 获得连接的方法
         */
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  ends ");

    }
    
    /**
     * 返回通知
     * 在方法正常结束之后返回的通知,r如出现异常,不会有返回
     * 返回通知是可以得到方法得到返回值的(调用方法的返回值)
     */
    @AfterReturning(value="execution(public int com.spring.aop.ArithmeticCalculator.*(..))",returning="result")
    public void afterReturn(JoinPoint joinPoint,Object result) {
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  ends with "+result);

    }
    /**
     * 异常通知
     * 在目标方法出现异常时会执行的代码,
     * 可以访问到异常对象,且可以指定在出现特定异常是执行通知代码(此处是出现NullPointerException异常时执行异常通知)
     */
    @AfterThrowing(value="execution(public int com.spring.aop.ArithmeticCalculator.*(..))",throwing="ex")
    public void afterThrowing(JoinPoint joinPoint,NullPointerException ex) {
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  occurs excetion:with "+ex);
    }
}
************************************************************************************
package com.spring.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        
        //创建Spring的IOC容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("application.xml");
        
        ArithmeticCalculator ac=(ArithmeticCalculator) ctx.getBean("arithmeticCalculatorLogging");
        System.out.println(ac.getClass().getName());
        
        int result=ac.add(1, 2);
        
        System.out.println(result);
        
        result=ac.div(3, 10);
        System.out.println(result);
        
    }

}
***********************************结果*********************************************
com.sun.proxy.$Proxy15
validate:[1, 2]
The Method add  begins with...[1, 2]
The Method  add  ends 
The Method  add  ends with 3
3
validate:[3, 10]
The Method div  begins with...[3, 10]
The Method  div  ends 
The Method  div  ends with 0
0

(三)重用切点表达式@Pointcut

切点表达式当中的代码很多时候是重用的,可以声明一个方法,用于声明切点表达式,一般该方法当中不需要接入其他的代码

package com.spring.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 写一个日志切面
 * @author laochaochunfengting
 *
 */
@Order(2)
@Component
@Aspect
public class LoggingAspect {
    
    /**
     * 声明一个方法,用于声明切点表达式,一般该方法当中不需要接入其他的代码
     * 使用@Pointcut来声明切点表达式
     * 后面的其他通知直接使用该方法名来引用当前的切入点表达式
     */
    @Pointcut("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
    public void declareJointPointExpression() {
        
    }
    

    /**
     * 要求com.spring.aop.ArithmeticCalculator接口的每一个实现类的每一个方法在执行之前都执行一段代码
     * 如果需要连接细节,则可以防疫个连接点的参数
     */
    @Before("declareJointPointExpression()")
    public void beforeMethod(JoinPoint joinPoint) {
        /**
         * 获得连接的方法
         */
        String joinMethod=joinPoint.getSignature().getName();
        //获得连接参数
        Object [] args=joinPoint.getArgs();
        
        System.out.println("The Method "+joinMethod+ "  begins with..."+Arrays.asList(args));
        
    }
    /**
     * 后置通知
     * 在方法执行之后执行(无论该方法是否出现异常)
     */
    @After("declareJointPointExpression()")
    public void AfterMethod(JoinPoint joinPoint) {
        /**
         * 获得连接的方法
         */
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  ends ");

    }
    
    /**
     * 返回通知
     * 在方法正常结束之后返回的通知,r如出现异常,不会有返回
     * 返回通知是可以得到方法得到返回值的(调用方法的返回值)
     */
    @AfterReturning(value="declareJointPointExpression()",returning="result")
    public void afterReturn(JoinPoint joinPoint,Object result) {
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  ends with "+result);

    }
    /**
     * 异常通知
     * 在目标方法出现异常时会执行的代码,
     * 可以访问到异常对象,且可以指定在出现特定异常是执行通知代码(此处是出现NullPointerException异常时执行异常通知)
     */
    @AfterThrowing(value="execution(public int com.spring.aop.ArithmeticCalculator.*(..))",throwing="ex")
    public void afterThrowing(JoinPoint joinPoint,NullPointerException ex) {
        String joinMethod=joinPoint.getSignature().getName();
        System.out.println("The Method  "+joinMethod+ "  occurs excetion:with "+ex);
    }
}
**********************************************************************************
package com.spring.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * 可以使用Order来指定切面的优先级,值越小优先级越高
 * 
 * @author laochaochunfengting
 *
 */
@Order(1)
@Aspect
@Component
public class VidationAspect {

    @Before("LoggingAspect.declareJointPointExpression()")
    public void validateArgs(JoinPoint joinPoint) {
        
        System.out.println("validate:"+Arrays.asList(joinPoint.getArgs()));
    }
}

三.基于xml的方式

注意:首先要引入aspectJ的jar包。

Spring当所有的切面和通知器都必须要放在一个<aop:config>内部,(可以配置包含多个<aop:config>元素),每一个<aop:config>可以包含pointcut,advisor和aspect元素(而且必须要按照这个顺序进行声明)

<?xml version="1.0" encoding="UTF-8"?>
<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 http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    
    <bean id="arithmeticCalculatorLoggingImpl" class="com.spring.aop.xml.ArithmeticCalculatorLoggingImpl">
    
    </bean>
    
    <!-- 配置切面的bean -->
    <bean id="loggingAspect" class="com.spring.aop.xml.LoggingAspect"></bean>
    
    <bean id="vidationAspect" class="com.spring.aop.xml.VidationAspect"></bean>
    
    <bean id="loggingAspectArround" class="com.spring.aop.xml.LoggingAspectArround"></bean>
    <!-- 配置AOP -->
    <aop:config>
        <!-- 配置切点表达式 -->
            <aop:pointcut expression="execution(public int com.spring.aop.xml.ArithmeticCalculator.*(..))" id="pointCutt"/>
            
            <!-- 配置切面及通知 -->
            <aop:aspect ref="loggingAspect" order="2">
                <aop:before method="beforeMethod" pointcut-ref="pointCutt"/>
                <aop:after method="AfterMethod" pointcut-ref="pointCutt"/>
                <aop:after-throwing method="afterThrowing" pointcut-ref="pointCutt" throwing="ex"/>
                <aop:after-returning method="afterReturn" pointcut-ref="pointCutt" returning="result"/>
            </aop:aspect>
            <aop:aspect ref="vidationAspect" order="1">
                <aop:before method="validateArgs" pointcut-ref="pointCutt"/>
            </aop:aspect>
            
            <!-- 环绕通知 -->
            <!-- 
                <aop:aspect ref="loggingAspectArround" >
                    <aop:before method="arroundMethod" pointcut-ref="pointCutt"/>
                </aop:aspect> 
            -->
    </aop:config>
    
    
</beans>

4.AOP当中的切点表达式

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容