Home Java javaTutorial SpringBoot integrated Spring aop example introduction

SpringBoot integrated Spring aop example introduction

May 16, 2018 am 09:46 AM
spring springboot introduce

This article mainly introduces the detailed explanation of SpringBoot's integration of Spring AOP. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Before we start, we first add the required jar packages to the project. The new Maven dependencies are as follows:

<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-aop</artifactId> 
</dependency>
Copy after login

Next, we get to the point. The notification types involved here are: pre-notification, post-final notification, post-return notification, post-exception notification, and wrap-around notification. Let's take a detailed look at how to add these notifications in SpringBoot.

First we create an Aspect aspect class:

@Component 
@Aspect 
public class WebControllerAop { 
 
}
Copy after login

Specify the pointcut point:

//匹配com.zkn.learnspringboot.web.controller包及其子包下的所有类的所有方法 
@Pointcut("execution(* com.zkn.learnspringboot.web.controller..*.*(..))") 
public void executeService(){ 
 
}
Copy after login

Then we create a Controller request processing class:

package com.zkn.learnspringboot.web.controller; 
 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
 
/** 
 * Created by zkn on 2016/11/19. 
 */ 
@RestController 
@RequestMapping("/aop") 
public class AopTestController { 
 
}
Copy after login

Pre-notification

Configure pre-notification:

/** 
 * 前置通知,方法调用前被调用 
 * @param joinPoint 
 */ 
@Before("executeService()") 
public void doBeforeAdvice(JoinPoint joinPoint){ 
  System.out.println("我是前置通知!!!"); 
  //获取目标方法的参数信息 
  Object[] obj = joinPoint.getArgs(); 
  //AOP代理类的信息 
  joinPoint.getThis(); 
  //代理的目标对象 
  joinPoint.getTarget(); 
  //用的最多 通知的签名 
  Signature signature = joinPoint.getSignature(); 
  //代理的是哪一个方法 
  System.out.println(signature.getName()); 
  //AOP代理类的名字 
  System.out.println(signature.getDeclaringTypeName()); 
  //AOP代理类的类(class)信息 
  signature.getDeclaringType(); 
  //获取RequestAttributes 
  RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 
  //从获取RequestAttributes中获取HttpServletRequest的信息 
  HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST); 
  //如果要获取Session信息的话,可以这样写: 
  //HttpSession session = (HttpSession) requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION); 
  Enumeration<String> enumeration = request.getParameterNames(); 
  Map<String,String> parameterMap = Maps.newHashMap(); 
  while (enumeration.hasMoreElements()){ 
    String parameter = enumeration.nextElement(); 
    parameterMap.put(parameter,request.getParameter(parameter)); 
  } 
  String str = JSON.toJSONString(parameterMap); 
  if(obj.length > 0) { 
    System.out.println("请求的参数信息为:"+str); 
  } 
}
Copy after login

Note: JoinPoint and RequestContextHolder are used here. The signature information of the notification can be obtained through JoinPoint, such as the target method name, target method parameter information, etc. Obtain request information and Session information through RequestContextHolder.

Next we add a request processing method in the Controller class to test the pre-notification:

@RequestMapping("/testBeforeService.do") 
public String testBeforeService(String key,String value){ 
 
  return "key="+key+" value="+value; 
}
Copy after login

The pre-notification interception result is as follows:

Post-return notification

The code for configuring post-return notification is as follows:

/** 
 * 后置返回通知 
 * 这里需要注意的是: 
 *   如果参数中的第一个参数为JoinPoint,则第二个参数为返回值的信息 
 *   如果参数中的第一个参数不为JoinPoint,则第一个参数为returning中对应的参数 
 * returning 限定了只有目标方法返回值与通知方法相应参数类型时才能执行后置返回通知,否则不执行,对于returning对应的通知方法参数为Object类型将匹配任何目标返回值 
 * @param joinPoint 
 * @param keys 
 */ 
@AfterReturning(value = "execution(* com.zkn.learnspringboot.web.controller..*.*(..))",returning = "keys") 
public void doAfterReturningAdvice1(JoinPoint joinPoint,Object keys){ 
 
  System.out.println("第一个后置返回通知的返回值:"+keys); 
} 
 
@AfterReturning(value = "execution(* com.zkn.learnspringboot.web.controller..*.*(..))",returning = "keys",argNames = "keys") 
public void doAfterReturningAdvice2(String keys){ 
 
  System.out.println("第二个后置返回通知的返回值:"+keys); 
}
Copy after login

Add response request in Controller Process the information to test the post-return notification:

@RequestMapping("/testAfterReturning.do") 
public String testAfterReturning(String key){ 
 
  return "key=: "+key; 
} 
@RequestMapping("/testAfterReturning01.do") 
public Integer testAfterReturning01(Integer key){ 
 
  return key; 
}
Copy after login

When the request is sent: http://localhost:8001/aop/testAfterReturning.do?key=testsss&value=855sss, the processing result is as shown in the figure:

When the request is sent to: http://localhost:8001/aop/testAfterReturning01.do?key=55553&value=855sss, the processing result is as shown in the figure:

Post exception notification

The configuration method of post exception notification is as follows:

/** 
 * 后置异常通知 
 * 定义一个名字,该名字用于匹配通知实现方法的一个参数名,当目标方法抛出异常返回后,将把目标方法抛出的异常传给通知方法; 
 * throwing 限定了只有目标方法抛出的异常与通知方法相应参数异常类型时才能执行后置异常通知,否则不执行, 
 *   对于throwing对应的通知方法参数为Throwable类型将匹配任何异常。 
 * @param joinPoint 
 * @param exception 
 */ 
@AfterThrowing(value = "executeService()",throwing = "exception") 
public void doAfterThrowingAdvice(JoinPoint joinPoint,Throwable exception){ 
  //目标方法名: 
  System.out.println(joinPoint.getSignature().getName()); 
  if(exception instanceof NullPointerException){ 
    System.out.println("发生了空指针异常!!!!!"); 
  } 
}
Copy after login

Configuration in Controller Response request processing class:

@RequestMapping("/testAfterThrowing.do") 
public String testAfterThrowing(String key){ 
 
  throw new NullPointerException(); 
}
Copy after login

The processing results of the post-exception notification method are as follows:

Post-final notification

The post-final notification is configured as follows:

/** 
 * 后置最终通知(目标方法只要执行完了就会执行后置通知方法) 
 * @param joinPoint 
 */ 
@After("executeService()") 
public void doAfterAdvice(JoinPoint joinPoint){ 
 
  System.out.println("后置通知执行了!!!!"); 
}
Copy after login

Controller class configures the corresponding request processing class:

@RequestMapping("/testAfter.do") 
public String testAfter(String key){ 
 
  throw new NullPointerException(); 
} 
@RequestMapping("/testAfter02.do") 
public String testAfter02(String key){ 
 
  return key; 
}
Copy after login

When the request is sent: http:// localhost:8001/aop/testAfter.do?key=55553&value=855sss

When sending the request: http://localhost:8001/aop/testAfter02.do?key =55553&value=855sss

Surround notification

Surround notification is configured as follows:

/** 
 * 环绕通知: 
 *  环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值。 
 *  环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型 
 */ 
@Around("execution(* com.zkn.learnspringboot.web.controller..*.testAround*(..))") 
public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ 
  System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName()); 
  try { 
    Object obj = proceedingJoinPoint.proceed(); 
    return obj; 
  } catch (Throwable throwable) { 
    throwable.printStackTrace(); 
  } 
  return null; 
}
Copy after login

The request processing class corresponding to the Controller is as follows:

@RequestMapping("/testAroundService.do") 
public String testAroundService(String key){ 
 
  return "环绕通知:"+key; 
}
Copy after login

When the request is sent: http://localhost:8001/aop/testAroundService.do?key=55553

When the request is sent to: http://localhost:8001/aop/testAfter02.do?key=55553&value=855sss, it does not comply with the cut-in rules of the surrounding notification, so the surrounding notification will not be executed.

The complete AOP configuration code is as follows:

package com.zkn.learnspringboot.aop; 
 
import com.alibaba.fastjson.JSON; 
import com.google.common.collect.Maps; 
import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.Signature; 
import org.aspectj.lang.annotation.*; 
import org.springframework.stereotype.Component; 
import org.springframework.web.context.request.RequestAttributes; 
import org.springframework.web.context.request.RequestContextHolder; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpSession; 
import java.util.Enumeration; 
import java.util.Map; 
 
/** 
 * Created by zkn on 2016/11/18. 
 */ 
@Component 
@Aspect 
public class WebControllerAop { 
 
  //匹配com.zkn.learnspringboot.web.controller包及其子包下的所有类的所有方法 
  @Pointcut("execution(* com.zkn.learnspringboot.web.controller..*.*(..))") 
  public void executeService(){ 
 
  } 
 
  /** 
   * 前置通知,方法调用前被调用 
   * @param joinPoint 
   */ 
  @Before("executeService()") 
  public void doBeforeAdvice(JoinPoint joinPoint){ 
    System.out.println("我是前置通知!!!"); 
    //获取目标方法的参数信息 
    Object[] obj = joinPoint.getArgs(); 
    //AOP代理类的信息 
    joinPoint.getThis(); 
    //代理的目标对象 
    joinPoint.getTarget(); 
    //用的最多 通知的签名 
    Signature signature = joinPoint.getSignature(); 
    //代理的是哪一个方法 
    System.out.println(signature.getName()); 
    //AOP代理类的名字 
    System.out.println(signature.getDeclaringTypeName()); 
    //AOP代理类的类(class)信息 
    signature.getDeclaringType(); 
    //获取RequestAttributes 
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 
    //从获取RequestAttributes中获取HttpServletRequest的信息 
    HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST); 
    //如果要获取Session信息的话,可以这样写: 
    //HttpSession session = (HttpSession) requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION); 
    Enumeration<String> enumeration = request.getParameterNames(); 
    Map<String,String> parameterMap = Maps.newHashMap(); 
    while (enumeration.hasMoreElements()){ 
      String parameter = enumeration.nextElement(); 
      parameterMap.put(parameter,request.getParameter(parameter)); 
    } 
    String str = JSON.toJSONString(parameterMap); 
    if(obj.length > 0) { 
      System.out.println("请求的参数信息为:"+str); 
    } 
  } 
 
  /** 
   * 后置返回通知 
   * 这里需要注意的是: 
   *   如果参数中的第一个参数为JoinPoint,则第二个参数为返回值的信息 
   *   如果参数中的第一个参数不为JoinPoint,则第一个参数为returning中对应的参数 
   * returning 限定了只有目标方法返回值与通知方法相应参数类型时才能执行后置返回通知,否则不执行,对于returning对应的通知方法参数为Object类型将匹配任何目标返回值 
   * @param joinPoint 
   * @param keys 
   */ 
  @AfterReturning(value = "execution(* com.zkn.learnspringboot.web.controller..*.*(..))",returning = "keys") 
  public void doAfterReturningAdvice1(JoinPoint joinPoint,Object keys){ 
 
    System.out.println("第一个后置返回通知的返回值:"+keys); 
  } 
 
  @AfterReturning(value = "execution(* com.zkn.learnspringboot.web.controller..*.*(..))",returning = "keys",argNames = "keys") 
  public void doAfterReturningAdvice2(String keys){ 
 
    System.out.println("第二个后置返回通知的返回值:"+keys); 
  } 
 
  /** 
   * 后置异常通知 
   * 定义一个名字,该名字用于匹配通知实现方法的一个参数名,当目标方法抛出异常返回后,将把目标方法抛出的异常传给通知方法; 
   * throwing 限定了只有目标方法抛出的异常与通知方法相应参数异常类型时才能执行后置异常通知,否则不执行, 
   *   对于throwing对应的通知方法参数为Throwable类型将匹配任何异常。 
   * @param joinPoint 
   * @param exception 
   */ 
  @AfterThrowing(value = "executeService()",throwing = "exception") 
  public void doAfterThrowingAdvice(JoinPoint joinPoint,Throwable exception){ 
    //目标方法名: 
    System.out.println(joinPoint.getSignature().getName()); 
    if(exception instanceof NullPointerException){ 
      System.out.println("发生了空指针异常!!!!!"); 
    } 
  } 
 
  /** 
   * 后置最终通知(目标方法只要执行完了就会执行后置通知方法) 
   * @param joinPoint 
   */ 
  @After("executeService()") 
  public void doAfterAdvice(JoinPoint joinPoint){ 
 
    System.out.println("后置通知执行了!!!!"); 
  } 
 
  /** 
   * 环绕通知: 
   *  环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值。 
   *  环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型 
   */ 
  @Around("execution(* com.zkn.learnspringboot.web.controller..*.testAround*(..))") 
  public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){ 
    System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName()); 
    try {//obj之前可以写目标方法执行前的逻辑 
      Object obj = proceedingJoinPoint.proceed();//调用执行目标方法 
      return obj; 
    } catch (Throwable throwable) { 
      throwable.printStackTrace(); 
    } 
    return null; 
  } 
}
Copy after login

The complete Controller class code is as follows:

package com.zkn.learnspringboot.web.controller; 
 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
 
/** 
 * Created by zkn on 2016/11/19. 
 */ 
@RestController 
@RequestMapping("/aop") 
public class AopTestController { 
 
  @RequestMapping("/testBeforeService.do") 
  public String testBeforeService(String key,String value){ 
 
    return "key="+key+" value="+value; 
  } 
  @RequestMapping("/testAfterReturning.do") 
  public String testAfterReturning(String key){ 
 
    return "key=: "+key; 
  } 
  @RequestMapping("/testAfterReturning01.do") 
  public Integer testAfterReturning01(Integer key){ 
 
    return key; 
  } 
  @RequestMapping("/testAfterThrowing.do") 
  public String testAfterThrowing(String key){ 
 
    throw new NullPointerException(); 
  } 
  @RequestMapping("/testAfter.do") 
  public String testAfter(String key){ 
 
    throw new NullPointerException(); 
  } 
  @RequestMapping("/testAfter02.do") 
  public String testAfter02(String key){ 
 
    return key; 
  } 
  @RequestMapping("/testAroundService.do") 
  public String testAroundService(String key){ 
 
    return "环绕通知:"+key; 
  } 
}
Copy after login

The above is the detailed content of SpringBoot integrated Spring aop example introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

See all articles