This is the 22nd day of my participation in the First Challenge 2022

Today because some function needs, needs to write some AOP, encountered some strange strange small problem, organizes, if everybody encountered, avoids everybody to step on pit

First, what is Aop, this.. I don’t think we need to talk about that

The first real step is to import our dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
Copy the code

When I use Springboot, importing this dependency works, and some posts on the web say adding it

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
Copy the code

This, everyone, can be determined according to their own situation

Next, let’s create a normal test class

@restController public Class testCon {@getMapping ("tt") public String TT (){return "TT test "; }}Copy the code

Then I’m going to create our section class

@Aspect @Component public class MyAop { @Before("execution(public * com.example.oj.controller.testCon.tt())") public void testBefore(){ System.out.println("Before--------"); }}Copy the code

Notice here that we add our two annotations

@aspect This is the annotation that represents our Aspect

@Component we also need to hand this class over to the Spring container to manage

We have a focus in this class

Is the @ Before (” execution (public * com. Example. Oj. Controller. TestCon. Tt ()) “)

Let’s look at our directory structure first

We’ve marked all the major classes in red, and then we’ll go back to the problem we just had

  1. Our parameters work"execution(public * com.example.oj.controller.testCon.tt(..) )"Can be any parameter
  2. The method name"execution(public * com.example.oj.controller.testCon.*(..) )"In ourtestConClass, any method, any parameter
  3. The name of the class"execution(public * com.example.oj.controller.*.*(..) )"In ourcontrollerAny class in the package, any method, any parameter
  4. Type, we can specify in this asterisk what type it is, like int, String, whatever
  5. And finally, the most important thing"execution(public * com.example.oj.controller.. *. * (..) )"When we look at the gap between it and our third item, we have one more point than him, which means that it is incontrollerUnder the bagAnd subpackagesAny class, any method, any parameter