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
- Our parameters work
"execution(public * com.example.oj.controller.testCon.tt(..) )"
Can be any parameter - The method name
"execution(public * com.example.oj.controller.testCon.*(..) )"
In ourtestCon
Class, any method, any parameter - The name of the class
"execution(public * com.example.oj.controller.*.*(..) )"
In ourcontroller
Any class in the package, any method, any parameter - Type, we can specify in this asterisk what type it is, like int, String, whatever
- 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 incontroller
Under the bagAnd subpackagesAny class, any method, any parameter