[10] AOP的註解配置


一、關於配置文件

首先在由於要使用到掃描功能,因此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>

二、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");
    }

}
相關文章
相關標籤/搜索