[10] AOP的注解配置


1、关于配置文件

首先在因为要使用到扫描功能,所以xml的头文件中除了引入bean和aop之外,还要引入context才行:
<?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:context="http://www.springframework.org/schema/context"
       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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    
    ...
    
</beans>    

既然使用注解,那么在配置文件中需要开启扫描配置以注册bean组件;同时Spring中使用了aspectj包的@Aspect注解标注当前组件为切面,所以同时还需要在配置文件中配置实用aspectj的自动代理模式。如下:
<!-- 开启bean组件扫描 -->
<context:component-scan base-package="dulk.learn"></context:component-scan>
<!-- 启用自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

2、AOP的注解配置

AOP的注解配置方式,对于一个类来说:
  • 通过 @Component 声明该类为bean组件
  • 通过 @Aspect 标记该类为切面
  • 通过注解说明类中函数的通知类型

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;


@Component
@Aspect
public class Section {

    @Before("execution(* dulk.learn..*.*(..))")
    public void doBefore(JoinPoint point) {
        System.out.println("doBefore");
    }

    @AfterReturning(pointcut = "execution(* dulk.learn..*.*(..))", returning = "ret")
    public void doAfterReturning(JoinPoint point, Object ret) {
        System.out.println("doAfterReturning");
        System.out.println("The returning obj is " + ret);
    }

    @AfterThrowing(pointcut = "execution(* dulk.learn..*.*(..))", throwing = "e")
    public void doThrow(JoinPoint point, Throwable e) {
        System.out.println("doThrow");
    }

    @After("execution(* dulk.learn..*.*(..))")
    public void doAfter() {
        System.out.println("doAfter");
    }

    @Around("execution(* dulk.learn..*.*(..))")
    public void doAround(ProceedingJoinPoint point) {
        System.out.println("doAround-dobefore");
        try {
            Object obj = point.proceed();
            System.out.println("doAround-doAfterReturning");
        } catch (Throwable throwable) {
            System.out.println("doAround-doThrow");
        }
        System.out.println("doAround-doAfter");
    }

}


原文地址:https://www.cnblogs.com/deng-cc/p/9225047.html