[JAVA] Spring AOP for the first time

This time, I would like to write about Spring AOP. If you want to know the detailed specifications, please read Official Reference. The version is Spring Boot 2.0.1.RELEASE (Spring 5.0.5.RELEASE).

What is AOP

AOP stands for ** Aspect Oriented Programming ** and is called "Aspect Oriented Programming". In AOP, write code to separate cross-class processing (exception handling, logging, transaction processing, etc.) from the business logic. This makes it possible to simply write multiple processes and prevent code that performs the same process from being written in various places.

Terms often used in Spring AOP

Aspect Aspect is a module that defines cross-cutting processing and where to perform it. In Spring, by adding @Aspect to a class, that class will be recognized as Aspect. You need to define Aspect as a bean, so don't forget to declare it as a bean with @Component. (@Service and @Repository where @Component is declared internally are also OK.)

@Component
@Aspect
public class HogeAspect{

}

JoinPoint JoinPoint refers to the place (method) where the cross-cutting process is inserted. PointCut PointCut is a representation of a collection of JoinPoints. As shown in the code example below, PointCut is expressed as an annotation parameter of Advice (described later). In the example of ↓, JoinPoint is specified by execution ().

@After(value = "execution(* com.example.fuga..Fuga.*(..))")
public void Hoge(/* .. */){
  /* .. */
}
/*In Spring, if there are no other parameters, the parameter named value "value"=Can be omitted, so
@After("execution(* com.example.fuga..Fuga.*(..))")You can also write.*/

In execution (), JoinPoint is expressed by the following grammar.

execution(Return value Package name.name of the class.Method name(Argument type))
/*
「*」 ->Represents an arbitrary character string. However, when used as a package name, it represents "one package with an arbitrary name", and when used as an argument, it represents "one arbitrary type".
「..」 ->When used as a package name, it represents "a package of 0 or more", and when used as an argument, it represents "any type of 0 or more".
*/ 

In the first example, it is expressed that @After is applied to all methods of the class "Fuga" under the "com.example.fuga" package (including subpackages) with an arbitrary return value. doing.

Besides execution (), there are various things such as within () and this (), but execution () is often used. Reference

Advice Advice represents the cross-cutting process itself performed by JoinPoint. By annotating the method of the class with @Aspect, that method can be executed as Advice. There are five types of annotations that represent Advice: @Before Advice that is executed before processing the target method.

@Before("execution(* *..*(..))")
public void beforeHandler(){
/* .. */
}

@After Advice that is always executed regardless of the processing result of the target method.

@After("execution(* *..*(..))")
public void afterHandler(){
/* .. */
}

@AfterReturning Advice that is executed only when the processing of the target method is completed correctly. If you specify a character string in the returning parameter, the return value of the process executed by JoinPoint is stored in the variable of that character string. This allows the return value to be used in Advice.

@AfterReturning(value = "execution(* *..*(..))", returning = "r")
public void afterReturning(Object r){
  System.out.println(r);
}

@AfterThrowing Advice that is executed only when an exception occurs while processing the target method. If you specify a string in the throwing parameter, the variable in that string will contain the exception that occurred in the process executed by JoinPoint. This allows exceptions to be used in Advice.

@AfterThrowing(value = "execution(* *..*(..))", throwing = "e")
public void afterThrowing(Throwable e){
  System.out.println(e.getMessage());
}

@Arround Advice that can be executed at any time before or after processing the target method. As shown in the example below, pre-processing and post-processing can be set freely.

@Arround("execution(* *..*(..))")
public void arround(ProceedingJoinPoint pjp) throws Throwable {
  System.out.println("Preprocessing")

  //Method execution
  Object result = pjp.proceed();

  System.out.println("Post-processing")
}

How to use

Add library to pom.xml

If you are using Spring Boot, add "spring-boot-starter-aop" to the dependencies of pom.xml. If "spring-boot-starter-parent" is specified as parent, it is not necessary to specify the version of spring-boot-starter-aop because the version information has already been defined.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
</dependencies>

If you are not using Spring Boot, you can use it by adding "spring-aop" and "aspectjweaver" to pom.xml and adding @EnableAspectJAutoProxy to JavaConfig (operation unconfirmed).

Create an Aspect

Create a class for Aspect and prefix the class with @Aspect and @Component.

@Component
@Aspect
public class HogeAspect{

}

Create Advice and write PointCut

Create a method in the class defined as Aspect. Annotate the Advice described above as appropriate according to the timing of executing the Advice. In addition, use execution () to describe in which class or method the created Advice is applied in the Advice annotation.

@Component
@Aspect
public class HogeAspect{
  
  @AfterThrowing(value = "execution(* *..*(..))", throwing = "ex")
  public void handler(Throwable ex){
    /* .. */
  }
}

In the example above, exception handling is defined for exceptions that occur in all methods.

reference

https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/core.html#aop

Recommended Posts

Spring AOP for the first time
Spring Boot for the first time
Introduction to java for the first time # 2
I tried using Docker for the first time
Walls hit by Rspec for the first time
I tried touching Docker for the first time
Learn for the first time java # 3 expressions and operators
Oreore certificate https (2020/12/19) for the first time with nginx
Try running Spring Cloud Config for the time being
Learning memo when learning Java for the first time (personal learning memo)
How to study kotlin for the first time ~ Part 2 ~
How to study kotlin for the first time ~ Part 1 ~
[Rails] I tried using the button_to method for the first time
Memo after the first Spring project-MVC-
Memo after the first Spring project-Database-
Modeling a Digimon with DDD for the first time Part 1
Think when Rails (turbolinks) doesn't load the page for the first time
Memo after the first Spring project-What is Spring-
Touching kotlin for the first time-Enum Classes
Use the l method for time notation
About Spring AOP
[First Java] Make something that works with Intellij for the time being
The story of releasing the Android app to the Play Store for the first time.
About spring AOP
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
Creating an app and deploying it for the first time on heroku
Programming for the first time in my life Java 1st Hello World
Matches annotations on the interface with Spring AOP
Install Amazon Corretto (preview) for the time being
Use Java external library for the time being
Run Dataflow, Java, streaming for the time being
The story of intentionally using try catch for the first time in my life
Impressions and doubts about using java for the first time in Android Studio
A story about a super beginner participating in the AtCoder contest for the first time (AtCoder Beginner Contest 140)
[For beginners] DI ~ The basics of DI and DI in Spring ~
First Spring Boot (DI)
About Spring AOP Pointcut
[Programming Encyclopedia] §1 First time programming
[First post] Output the characters Sold Out for sold products
[CircleCI] I will explain the stupid configuration file (config.yml) that I wrote for the first time.
[Android studio / Java] What you don't understand when you touch it for the first time
Command to try using Docker for the time being
Overview of Spring AOP
Change the injection target for each environment with Spring Boot 2
Hello World with Ruby extension library for the time being
The first WEB application with Spring Boot-Making a Pomodoro timer-
Beginner-friendly Android app publishing procedure, struggling for the first release⁈
With the software I've been making for a long time ...
[DL4J] Java deep learning for the first time (handwriting recognition using a fully connected neural network)
[Introduction] Installation of Docker Desktop for Mac for the first time and setup of virtual environment construction of CentOS
[Java] Spring AOP execution order
[Introduction] Setting up GridDB Community Edition in the CentOS container of Docker Desktop for the first time
Build Spring for Android 2.0.0 environment
What is the constructor for?
Try the Spring WebFlux tutorial
Spring Boot for annotation learning
Java14 came out, so I tried record for the time being
What an inexperienced person is thinking now after a month of self-taught programming for the first time.
Let's experience the authorization code grant flow with Spring Security OAuth-Part 2: Creating an app for the time being
[Ruby on Rails] When logging in for the first time ・ How to split the screen in half using jQuery