Preface
Brother Yang of Jianghu once said this:
Using technology in the current environment is nothing more than just a few steps:
1. Introduce POM (maven) coordinates
2. Change yml (configuration file can also be properties, etc.)
3. Write configuration class or add annotations on the startup class
4. Just write the code and finish it
Tip: The following is the main content of this article, and the following cases are for reference
1. Be familiar with related concepts:
In Spring AOP, the annotation is
The main ways to define Aspects, Pointcuts, notifications, etc.
Here are several common annotations in Spring AOP, their uses and how to use them:
1、@Aspect:
- Function: Identify a class as a facet class.
- How to use: Annotate this annotation on a class, which will contain definitions of tangents and notifications.
- Example
Example:
@Aspect public class MyAspect { // Definition of tangent and notification...}
2、@Pointcut:
- Function: Define a tangent point, that is, the entrance to the cross-cutting point of concern, and clarify what kind of method calls will be intercepted.
- How to use: Use this annotation before the method declaration and provide a point-tangent expression, which itself is usually an empty method, only as a reference to the point-tangent.
- Example:
@Aspect public class MyAspect { @Pointcut("execution(* .*.*(..))") public void serviceMethod() {} // Other notices...}
3、@Before:
- Function: Define a pre-notification that is executed before the method of tangent is executed.
- How to use: Put this annotation on a method that will be executed before the target method is executed.
- Example:
Example:
@Aspect public class MyAspect { @Before("serviceMethod()") public void beforeServiceMethod() { // Pre-logic... } }
4、@AfterReturning:
- Function: Define a notification after return, and execute after the tangent method returns normally.
- How to use: Put this annotation on a method and record the returned value through the parameters provided by the method.
- Example:
@Aspect public class MyAspect { @AfterReturning(pointcut = "serviceMethod()", returning = "retVal") public void afterReturning(Object retVal) { // Process the return value... } }
5、@AfterThrowing:
- Function: Define an exception notification, if the point-cut method throws an exception and executes it.
- How to use: Put this annotation on a method and optionally get the thrown exception.
- Example:
@Aspect public class MyAspect { @AfterThrowing(pointcut = "serviceMethod()", throwing = "ex") public void afterThrowing(Exception ex) { // Exception handling... } }
6、@After:
- Function: Define a final notification, which will be executed regardless of whether the point-cut method returns normally or throws an exception.
- How to use: Put this annotation on a method that will be executed regardless of the target method.
- Example:
Example:
@Aspect public class MyAspect { @After("serviceMethod()") public void afterServiceMethod() { // The final logic... } }
7、@Around:
- Function: Define a surround notification that can customize the logic executed before and after the target method, while deciding whether to continue executing the target method.
- How to use: Put this annotation on a method, which needs to return an Object, which may be the return value of the target method or the return value you have customized. You can call the target method directly in this method.
- Example:
@Aspect public class MyAspect { @Around("serviceMethod()") public Object aroundServiceMethod(ProceedingJoinPoint pjp) throws Throwable { // Pre-logic... Object result = (); // Execute the target method // Post-logic... return result; } }
There are usually two ways to use Spring AOP:
By annotation-driven method: use @EnableAspectJAutoProxy annotation on the configuration class to enable AOP support, and then declare the facet class and related annotations.
The way to configure XML: define the aop:config element in the XML file, and configure the facets and notifications inside the element.
Generally speaking, the annotation-driven method is more concise and intuitive, and is the recommended method. However, XML configuration methods may still be used in some use cases or old projects.
2. Specific use case:
Of course, let's take a simple AOP use case as an example to implement a section that records the execution time of the method. First make sure your project has been added to Spring AOP-related dependencies. For example, when using Maven, you can add the following dependencies to your file:
document
<!-- Spring AOP rely --> <dependency> <groupId></groupId> <artifactId>spring-aop</artifactId> <version>5.3.18</version> </dependency> <!-- AOPallianceAPI --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- SpringPart of the framework,For processingAOPAgent --> <dependency> <groupId></groupId> <artifactId>spring-aspects</artifactId> <version>5.3.18</version> </dependency>
2. Code
Now, let's create a section that records when the method is executed:
// Classes with @Aspect annotation will be recognized by Spring as a tangent@Aspect // Make sure this class is scanned by Spring's container, usually it should be in a package or subpackage specified by @ComponentScan@Component public class PerformanceAspect { // Point-tangent expression, here refers to any method in the Service layer that returns arbitrary value @Pointcut("execution(* .*.*(..))") public void serviceMethod() {} // Surround notifications, allowing us to add custom logic before and after method execution @Around("serviceMethod()") public Object profile(ProceedingJoinPoint pjp) throws Throwable { long start = (); // Start time Object output = (); // Execute the proxy method long elapsedTime = () - start; // Calculate the time consumed ("Method execution time: " + elapsedTime + " milliseconds."); return output; // Return the return value of the proxy method } }
Then, you need to add the following content to the Spring configuration class to enable the automatic proxy function of AOP:
@Configuration @EnableAspectJAutoProxy @ComponentScan("") // Modify to your package namepublic class AppConfig { // Additional Bean configuration can be added...}
Now your AOP section is ready. When your program runs, any method matching Pointcut (any method located in the package) will be intercepted by PerformanceAspect, which records the execution time before and after the method is executed and prints that time to the console.
Suppose we have a simple service class:
package ; import ; @Service public class SimpleService { public void doSomething() { // Simulate business logic processing time try { (1000); } catch (InterruptedException e) { ().interrupt(); } } }
When you call the doSomething method of the SimpleService class, the above PerformanceAspect will automatically intercept the call and record the execution time of the method. This way you complete an AOP entry-level case for Spring.
Summarize
OK, let's develop and use it as much as possible. In fact, this is prepared for me to write the article on that interview question hahahahaha
This is the end of this article about the complete implementation process of springAOP. For more related springAOP implementation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!