笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

Spring boot AOP使用笔记

Posted on 2024-04-13 18:00  草妖  阅读(7)  评论(0)    收藏  举报

 

图片来源:springAOP - 教程 - wzzkaifa - 博客园 (cnblogs.com)

image

 

 

 

对指定类进行AOP

pom.xml

<!-- 引入aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

PublicController.java

package com.namejr.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/Public")
public class PublicController {
    @RequestMapping(value = "/getString", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public String getString(String name) {
        System.out.println("getString...");
        return name+",嗷嗷嗷";
    }
}
WriteAspectDemo.java
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class WriteAspectDemo {
    @Pointcut("execution(public * com.namejr.controller..*.*(..))")
    public void aspectPointFunc(){}

    @Before("aspectPointFunc()")
    public void breforePoint(JoinPoint jpoint){
        System.out.println("breforePoint...");
    }

    @After("aspectPointFunc()")
    public void afterPoint(JoinPoint jpoint){
        System.out.println("afterPoint...");
    }

    @Around("aspectPointFunc()")
    public Object aroundPoint(ProceedingJoinPoint jpoint) {
        try {
            System.out.println("aroundPoint...start...");
            // 执行
            Object result = jpoint.proceed();
            System.out.println("aroundPoint...end...");
            return result;
        } catch (Throwable ignored) {}
        return null;
    }

    @AfterReturning("aspectPointFunc()")
    public void afterReturningPoint(JoinPoint jpoint) {
        System.out.println("afterReturningPoint...");
    }

    @AfterThrowing(value = "aspectPointFunc()", throwing = "tInfo")
    public void afterThrowingPoint(JoinPoint jpoint, Throwable tInfo) {
        System.out.println(tInfo.getMessage());
        System.out.println("afterThrowingPoint...");
    }
}

访问路径:127.0.0.1:8080/api/Public/getString?name=namejr

输出:

aroundPoint...start...
breforePoint...
getString...
afterReturningPoint...
afterPoint...
aroundPoint...end...

  

对指定注解进行AOP

 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.2</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <groupId>com.namejr</groupId>
  <artifactId>SBAOPDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SBAOPDemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 引入aop -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.yml</include>
          <include>**/*.xml</include>
          <include>**/*.json</include>
          <include>**/*.js</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <!-- 注册webapp目录为资源目录 -->
        <directory>src/main/webapp</directory>
        <targetPath>META-INF/resources</targetPath>
        <includes>
          <include>**/**</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <includeSystemScope>true</includeSystemScope>
          <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
        </configuration>
      </plugin>
      <plugin>
        <!-- 配置jar包打包工具 -->
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
          <webResources>
            <resource>
              <directory>${project.basedir}/libs</directory>
              <targetPath>WEB-INF/lib</targetPath>
              <includes>
                <include>**/*.jar</include>
              </includes>
            </resource>
          </webResources>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

写一个注解(InterfaDemo.java

package com.namejr;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface InterfaDemo {
}

写一个针对注解的AOP

package com.namejr;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class WriteAspectDemo {
    @Around("@annotation(InterfaDemo)")
    public Object aroundPoint(ProceedingJoinPoint jpoint) {
        try {
            Object[] args = jpoint.getArgs(); // 获取方法参数
            for (Object arg : args) {
                /* *
                 * 按接收位置接收为Object[]
                 * GET:
                 *  PublicController控制器里的函数:public String testGetMethod(String userID,String userName){},
                 *  哪怕传递请求是:http://127.0.0.1:8080/api/DecryptPublic/testGetMethod?userName=namejr1&userID=nid,
                 *  Object[]接收的顺序都是:第一个(下标0)的值是userID的值,第二个的值才是userName的值
                 * POST:
                 *  循序同GET,只不过POST接收是模型时,对应的Object表示的是模型
                * */
                System.out.println("参数: " + arg);
            }
            System.out.println("aroundPoint...start...");
            MethodSignature signature = (MethodSignature) jpoint.getSignature();
            Object result= jpoint.proceed();
            if (signature.getMethod().isAnnotationPresent(InterfaDemo.class)) {
                System.out.println("InterfaDemo...running...");
                // 方法上有@InterfaDemo注解,可以做日志记录啥的,这里也可以使用@After
            }
            System.out.println("aroundPoint...end...");
            return result;
        } catch (Throwable ignored) {}
        return null;
    }
}

写一个控制器调用

package com.namejr;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/DecryptPublic")
public class PublicController {
    @InterfaDemo
    @RequestMapping(value = "/testGetMethod", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String testGetMethod(String userID,String userName) {
        return userID+":"+userName + ",testGetMethod...";
    }

    @InterfaDemo
    @RequestMapping(value = "/testPostMethod", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String testPostMethod(@RequestBody UserModel model) {
        return model.userID+":"+model.userName + ",testGetMethod...";
    }
}

调用输出