[JAVA] I want to pass the argument of Annotation and the argument of the calling method to aspect

Introduction

This is a story about AOP of Java Spring Framework.

Use of @Aspect

For example, there are 100 classes that want to use a certain Service class, and it can be realized by adding @Autowired each time and DI, but it is not very smart. Therefore, define the process you want to perform in various places (class with @ Aspect annotation), and add annotation to the method of the class you want to use it to improve the visibility of the source code. That is the purpose.

Confirmation of terms

  1. ʻAspect` The module itself that shows cross-cutting interests.
  2. Join Point A point that executes a cross-cutting concern (at the time of method execution or exception throw).
  3. ʻAdviceThe code that runs at a particular JoinPoint, the implementation of cross-cutting concerns.@Around` is highly versatile, but if you want to limit the timing such as processing that you want to perform only when the processing of the target method is successful, you should use Advice that suits your purpose.
@Before Processed before processing the target method
@AfterReturning Processed when the target method is successfully processed
@AfterThrowing Processed when an exception is thrown in the processing of the target method
@After: Processed when the process is completed regardless of the success or failure of the process of the target method
@Around Executed before and after processing the target method
  1. pointcut An expression that selects the JoinPoint to be executed. You can narrow down the execution timing in detail by specifying the conditions. I will not touch it this time. The following will be helpful. https://qiita.com/rubytomato@github/items/de1019aeaaab51c8784d

Concrete example

Controller using Aspect

MyController.java


@Controller
@RequestMapping("/hogehoge")
public class MyController {

    @GetMapping
    @MyAnnotation(hoge = "test", piyo = false)
    public String doGet(HttpServletRequest req, HttpServletResponse res) {
        //~ Processing ~
        return "hogehoge";
    }
}

Definition of Annotation

This area was helpful. https://itsakura.com/java-annotation-make Primitive type, String, Class, enumeration type, annotation, and only one-dimensional array of them can be specified as arguments. https://www.ne.jp/asahi/hishidama/home/tech/java/annotation.html

MyAnnotation.java


//Annotation scope.
@Retention(RetentionPolicy.RUNTIME)
//Target to which you want to give Annotation.
@Target(ElementType.METHOD)
public @interface MyAnnotation {

    /**String*/
    String hoge();

    /** boolean */
    boolean piyo();
}

Aspect that receives the definition of Annotation as an argument

MyAspect.java


@Aspect
@Component
public class MyAspect {

    @AfterReturning("@annotation(myAnnotation)")
    public void after(JoinPoint jp, MyAnnotation myAnnotation) throws Throwable {
        //Try to receive the caller's arguments
        //Here, you can get the caller's HttpServletRequest req and HttpServletResponse res.
        Object[] o = jp.getArgs();
        
        //Can accept Annotation arguments
        String hoge = myAnnotation.hoge();
        System.out.println(hoge); // test
        boolean piyo = myAnnotation.piyo();
        System.out.println(piyo); // false
    }
}

Summary

--Can receive the argument of the calling method, but cannot process the variable name as the key because it is the "value" of the argument

If you want to get the arguments of the calling method
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest()
                .getParameter("hoge");
    }

--Variables cannot be passed as arguments of Annotation (arguments) Primitive type, String, Class, enumeration type, annotation, and only one-dimensional array of them can be specified. ) --The writing method is slightly different depending on whether the Annotation argument is used or not. --When using, follow the sample code above --When not used @AfterReturning ("@ annotation (jp.ne.example.MyAnnotation)") (describe the full path of the annotation class)

Recommended Posts

I want to pass the argument of Annotation and the argument of the calling method to aspect
I want to expand the clickable part of the link_to method
I want to call a method and count the number
I want to output the day of the week
I want to var_dump the contents of the intent
[Ruby] I want to extract only the value of the hash and only the key
I want to control the start / stop of servers and databases with Alexa
I want to recursively get the superclass and interface of a certain class
I want to call a method of another class
I want to know the answer of the rock-paper-scissors app
I want to display the name of the poster of the comment
I want to call the main method using reflection
[Rough commentary] I want to marry the pluck method
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
Pass arguments to the method and receive the result of the operation as a return value
I tried to summarize the basics of kotlin and java
I want to bring Tomcat to the server and start the application
I want to change the log output settings of UtilLoggingJdbcLogger
I want to narrow down the display of docker ps
I want to return multiple return values for the input argument
[Ruby] I want to reverse the order of the hash table
I want to temporarily disable the swipe gesture of UIPageViewController
I want to pass the startup command to postgres with docker-compose.
I tried to explain the method
I want to get a list of the contents of a zip file and its uncompressed size
I want to understand the flow of Spring processing request parameters
I want to return to the previous screen with kotlin and java!
The story of Collectors.groupingBy that I want to keep for posterity
Method to add the number of years and get the end of the month
I want to limit the input by narrowing the range of numbers
I tried to summarize the methods of Java String and StringBuilder
I want to control the default error message of Spring Boot
I want to change the value of Attribute in Selenium of Ruby
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
I wanted to add @VisibleForTesting to the method
I was addicted to the roll method
I want to display the number of orders for today using datetime.
I want to display images with REST Controller of Java and Spring!
I want to know the JSP of the open portlet when developing Liferay
I tried to summarize the key points of gRPC design and development
[Active Admin] I want to customize the default create and update processing
I want to get the field name of the [Java] field. (Old tale tone)
I translated the grammar of R and Java [Updated from time to time]
I want you to use Enum # name () for the Key of SharedPreference
I tried to measure and compare the speed of GraalVM with JMH
[RxSwift] I want to deepen my understanding by following the definition of Observable
I want to get the value of Cell transparently regardless of CellType (Apache POI)
I compared the characteristics of Java and .NET
[Ruby] I want to do a method jump!
When you want to use the method outside
Output of how to use the slice method
[Ruby] I want to make an array from a character string with the split method. And vice versa.
I want to truncate after the decimal point
I want to separate the handling of call results according to the API caller (call trigger)
I want to see the contents of Request without saying four or five
When reassigning to an argument in a Ruby method and then calling `super` → The reassigned one is used
[JDBC ③] I tried to input from the main method using placeholders and arguments.
I want to get the value in Ruby
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
Since the argument of link_to is nil (null) and an unexpected link was generated, I tried to verify it