Spring AOP用法详解

 

什么是AOP

AOP:Aspect Oriented Programming,中文翻译为”面向切面编程“。面向切面编程是一种编程范式,它作为OOP面向对象编程的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、权限控制、缓存控制、日志打印等等。AOP采取横向抽取机制,取代了传统纵向继承体系的重复性代码
AOP把软件的功能模块分为两个部分:核心关注点横切关注点。业务处理的主要功能为核心关注点,而非核心、需要拓展的功能为横切关注点。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点进行分离
使用AOP有诸多好处,如:
1.集中处理某一关注点/横切逻辑
2.可以很方便的添加/删除关注点
3.侵入性少,增强代码可读性及可维护性

AOP的术语

1.Join point(连接点)
Spring 官方文档的描述:

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

程序执行过程中的一个点,如方法的执行或异常的处理。在Spring AOP中,连接点总是表示方法的执行。通俗的讲,连接点即表示类里面可以被增强的方法
2.Pointcut(切入点)

Pointcut are expressions that is matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points and Spring framework uses the AspectJ pointcut expression language

切入点是与连接点匹配的表达式,用于确定是否需要执行通知。切入点使用与连接点匹配的不同类型的表达式,Spring框架使用AspectJ切入点表达式语言。我们可以将切入点理解为需要被拦截的Join point
3.Advice(增强/通知)
所谓通知是指拦截到Joinpoint之后所要做的事情就是通知,通知分为前置通知、后置通知、异常通知、最终通知和环绕通知(切面要完成的功能)
4.Aspect(切面)
Aspect切面表示Pointcut(切入点)和Advice(增强/通知)的结合

Spring AOP用法

示例代码

/**  * 设置登录用户名  */ public class CurrentUserHolder {      private static final ThreadLocal<String> holder = new ThreadLocal<>();      public static String get() {         return holder.get();     }     public static void set(String user) {         holder.set(user);     } } /**  * 校验用户权限  */ @Service("authService") public class AuthServiceImpl implements AuthService {      @Override     public void checkAccess() {         String user = CurrentUserHolder.get();          if(!"admin".equals(user)) {             throw new RuntimeException("该用户无此权限!");         }     } } /**  * 业务逻辑类  */ @Service("productService") public class ProductServiceImpl implements ProductService {      @Autowired     private AuthService authService;      @Override     public Long deleteProductById(Long id) {         System.out.println("删除商品id为" + id + "的商品成功!");         return id;     }      @Override     public void deleteProductByName(String name) {         System.out.println("删除商品名称为" + name + 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信