Spring中通过Annotation来实现AOP

一、Spring配置文件

<!--通过@AspectJ注解的形式来使用Spring AOP,强制使用CGLIB代理-->
<aop:aspectj-autoproxy proxy-target-class="true"/>

Spring默认不支持@AspectJ风格的切面声明,通过aop命名空间的<aop:aspectj-autoproxy/>声明自动为spring容器中那些配置@Aspect切面的bean创建代理,织入切面。proxy-target-class="true",强制使用CGLIB代理(没有接口也可以生成代理类,JDK代理是必须有接口的)。

二、定义方面类(aspect)

package aop;

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;

/**
 * 定义一个方面(Aspect),Maven需要引用spring-aspects
 * 这个方面(Aspect)包括了多个增加处理(通知,比如:前置、后置、后置返回、异常等)
 *
 * @author xfyou
 * @date 2018/9/29
 */
@Aspect
@Component
public class Advice {

    @Before(value = "execution(* bean.*.*(..)) && args(arg0)", argNames = "arg0")
    public void beforeAdvice(String arg0) {
        System.out.println("arg0=" + arg0);
    }

    @AfterReturning(pointcut = "execution(* bean.*.*(..))", returning = "retVal")
    public void afterReturnAdvice(String retVal) {
        System.out.println("fristName=" + retVal);
    }

    @AfterThrowing(pointcut = "execution(* bean.*.*(..))", throwing = "ex")
    public void afterThrowingAdvice(Exception ex) {
        System.err.println(ex.getMessage());
    }

}

上面分别定义了三个“前置”、“后置返回”、“异常”增强处理(或者叫着:通知)方法。通过@Aspect标注的Advice类必须注册到Spring容器中才能使用,所以我们这里使用到了一个@Component注解让Spring能够自动扫描并注册到Spring容器中。

三、测试

package bean;

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

/**
 * @author xfyou
 * @date 2018/9/6
 */
public class Test {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
        Person person = context.getBean(Person.class);
        person.setFirstName("frank");
        person.getFirstName();
        person.test();
    }

}

输出如下:

beforeAdvice,arg0=frank
afterReturnAdvice,retVal=frank
afterThrowingAdvice,exception:RuntimeException
Exception in thread "main" java.lang.RuntimeException: RuntimeException
    at bean.Person.test(Person.java:18)
    at bean.Person$$FastClassBySpringCGLIB$$40dc9373.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

java动态代理:

参考:https://blog.csdn.net/luanlouis/article/details/24589193

原文地址:https://www.cnblogs.com/frankyou/p/9723545.html