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)

 

转载于:https://www.cnblogs.com/frankyou/p/9723545.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值