SpringAOP
Why should we use AOP (Aspect Oriented Programming)? When we complete the actual project in reality, we always need to perform some operations before, during, or after an "action", such as when we are running the program, we want to save the log, or in A sentence is output after each method call, which means that we need to perform the same operation every time we perform an "action", which causes programmers to perform a large number of useless repetitive actions. In this situation, AOP Came into being.
AOP overview
AOP, the abbreviation of Aspect Oriented Rrogramming, means: aspect-oriented programming, a technology that achieves unified maintenance of program functions through pre-compilation and dynamic agents during runtime. AOP can isolate each part of the business drain, so that the coupling between business logic is reduced, the reusability of the program is improved, and the development efficiency is improved at the same time.
AOP and OOP are two different design ideas. OOP (Object-Oriented Programming) abstracts the encapsulation of entities and their attributes and behaviors in the business process to obtain clear and efficient logical unit divisions. AOP is to extract aspects in the business processing process. It is to face a certain step or stage in the business processing process to obtain the isolation effect of low coupling between the various parts of the logic process.
The benefits of aspect-oriented programming are: reduce duplication and focus on business. It is a supplement to object-oriented programming.
personally sorted out some information, friends in need can click to get it directly.
Java learning routes and materials from 0 to 1
Core principles and use cases
Principle: Use dynamic proxy to add relevant logic before and after the execution of the method or when an exception occurs.
use:
事务处理:开启事务,关闭事务,出现异常回滚事务.....
权限判断:执行方法前,判断是否具有权限;
日志处理;
......
事务处理:开启事务,关闭事务,出现异常回滚事务.....
权限判断:执行方法前,判断是否具有权限;
日志处理;
......
The basic concepts of AOP (Spring terminology)
0. Enhancement: Inject some logic codes into each program to enhance the functions of the original program.
1. Connection point (JoinPoint): A method in a class that can be enhanced. This method is called a connection point. Remember that the connection point is not necessarily enhanced.
2. Pointcut: The method that is actually enhanced in the class.
3. Advice: Refers to what an aspect has to do at a specific connection point, which is simply "enhancement". It can be divided into notification before method execution, notification after method execution, surround notification and so on.
4. Aspect: The process of adding notifications to the point of entry is called aspect.
5. Target: The target object of the agent, that is, the class where the method to be enhanced is located.
6. Proxy: The proxy object created after the notification is applied to the target object.
SpringAOP implementation
Many frameworks have implemented the programming idea of AOP. Spring is just one of them, which can complete aspect-oriented programming. AspectJ is also an aspect-oriented framework, and its implementation is simpler and more convenient, and it supports annotation-based development. Therefore, Spring introduced AspectJ's implementation of AOP into its own framework.
When using AOP to develop in Spring, the implementation of AspectJ is usually used. There are five types of commonly used notifications:
- Pre-notification: execute before the method is executed;
- Post notification: execute after the method is executed;
- Surround notification: both before and after execution;
- Exception notification: notify when an exception occurs;
- Final notice: such as execution after return.
Use of SpringAOP
Import the AspectJ jar that implements AOP
<!--Spring实现AOP是依靠Aspects框架实现-->
<!--Aspects相关jar-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
Implementation of xml configuration based on AspectJ
All configuration is done in the spring.xml file.
1. Create a class with enhanced functionality.
import org.aspectj.lang.ProceedingJoinPoint;
//通知(Advice):在连接点要做的事情
public class Aop {
public void doLog() {
System.out.println("=====保存日志=====");
}
public void commit() {
System.out.println("=====提交事务=====");
}
public void around(ProceedingJoinPoint proceedingJoinPoint) {
System.out.println("======方法前通知======");
try {
proceedingJoinPoint.proceed();//调用自己的方法
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("======方法后通知======");
}
public void throwable(Throwable throwable) {
System.out.println("======出异常了======");
System.out.println(throwable.getMessage());
}
}
2. Hand over the classes with enhanced functions to spring for management
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--把装有通知(Advice)的类交给Spring管理-->
<bean id="aop" class="com.cwd.spring4pro.demo1.aop.Aop"></bean>
<!--在这里进行织入,即切面(Aspect):将通知添加到切入点-->
</beans>
3. Configuration aspect (Aspect)
First prepare an enhanced class, namely the target (Target)
import org.springframework.stereotype.Component;
//目标(Target):代理的目标对象,即要增强的类
@Component(value = "target")
public class Target {
/*
连接点(Joinpoint),可以被增强的方法
切入点(pointcut),实际被增强的方法,被增强了
*/
public void pointCut() {
System.out.println("这是一个保存的操作!!!");
return;
}
}
Add notifications to the entry point.
<!--织入-->
<aop:config>
<!--
配置切入点
execution表达式 前*表示返回值 saveUser(..)表示要增强的方法 ..表示参数
-->
<aop:pointcut id="pointCut" expression="execution(* com.cwd.spring4pro.demo.Target.pointCut(..))"/>
<!--配置通知 ref中引用的是通知类的id-->
<aop:aspect ref="aop">
<!--前置通知-->
<aop:before method="doLog" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
Five notification types configuration
1. Pre-notification
<!--织入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.cwd.spring4pro.demo.Target.pointCut(..))"/>
<aop:aspect ref="aop">
<!--前置通知-->
<aop:before method="doLog" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
2. Post notification
<!--织入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.cwd.spring4pro.demo.Target.pointCut(..))"/>
<aop:aspect ref="aop">
<!--后置通知-->
<aop:after method="commit" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
3. Surround notification
<!--织入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.cwd.spring4pro.demo.Target.pointCut(..))"/>
<aop:aspect ref="aop">
<!--环绕通知-->
<aop:around method="around" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
4. Exception notification
public void pointCut() {
System.out.println("这是一个保存的操作!!!");
int a = 10 / 0;
return;
}
<!--织入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.cwd.spring4pro.demo.Target.pointCut(..))"/>
<aop:aspect ref="aop">
<!--异常通知-->
<aop:after-throwing method="throwable" pointcut-ref="pointCut" throwing="throwable"/>
</aop:aspect>
</aop:config>
5. Final notice
<!--织入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.cwd.spring4pro.demo.Target.pointCut(..))"/>
<aop:aspect ref="aop">
<!--最终通知-->
<aop:after-returning method="commit" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
The final notification is generally executed after the return.
Annotation implementation
Turn on aop annotation scanning
<!--开启注解标签-->
<aop:aspectj-autoproxy/>
Configure in the notification class as follows:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component//将这个类交给Spring管理
@Aspect//标注这个类时装有通知的类
public class Aop {
@Before("execution(* com.cwd.spring4pro.demo.Target.pointCut(..))")
public void doLog() {
System.out.println("=====保存日志=====");
}
@After("execution(* com.cwd.spring4pro.demo.Target.pointCut(..))")
public void commit() {
System.out.println("=====提交事务=====");
}
public void around(ProceedingJoinPoint proceedingJoinPoint) {
System.out.println("======方法前通知======");
try {
proceedingJoinPoint.proceed();//调用自己的方法
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("======方法后通知======");
}
@AfterThrowing(value = "execution(* com.cwd.spring4pro.demo.Target.pointCut(..))",throwing = "throwable")
public void throwable(Throwable throwable) {
System.out.println("======出异常了======");
System.out.println(throwable.getMessage());
}
@AfterReturning("execution(* com.cwd.spring4pro.demo.Target.pointCut(..))")
public void returnAfter() {
System.out.println("======return后=====");
}
}
At last
I have seen it here. If you think the article is helpful to you, remember to like it, thank you for your support!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。