详解Spring中AOP

AOP (Aspect Orient Programming),直译过来就是 面向切面编程。AOP 是一种编程思想,是面向对象编程(OOP)的一种补充。面向对象编程将程序抽象成各个层次的对象,而面向切面编程是将程序抽象成各个切面。

在Spring中AOP包含两个概念,一是Spring官方基于JDK动态代理和CGLIB实现的Spring AOP;二是集成面向切面编程神器AspectJ。Spring AOP和AspectJ不是竞争关系,基于代理的框架的Spring AOP和成熟框架AspectJ都是有价值的,它们是互补的。

Spring无缝地将Spring AOP、IoC与AspectJ集成在一起,从而达到AOP的所有能力。Spring AOP默认将标准JDK动态代理用于AOP代理,可以代理任何接口。但如果没有面向接口编程,只有业务类,则使用CGLIB。当然也可以全部强制使用CGLIB,只要设置proxy-target-class=”true”。

AOP中的术语

通知(Advice)

Spring切面可以应用5种类型的通知:

前置通知(Before):在目标方法被调用之前调用通知功能;

后置通知(After):在目标方法完成之后调用通知,此时不会关心方法的输出是什么;

返回通知(After-returning):在目标方法成功执行之后调用通知;

异常通知(After-throwing):在目标方法抛出异常后调用通知;

环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。

连接点(Join point)

切点(Poincut)

切面(Aspect)

引入(Introduction)

织入(Weaving)

这些术语的解释,其他博文中很多,这里就不再赘述。

用2个例子来说明Spring AOP和AspectJ的用法

现在有这样一个场景,页面传入参数当前页page和每页展示多少条数据rows,我们需要写个拦截器将page、limit参数转换成MySQL的分页语句offset、rows。

先看Spring AOP实现

1、实现MethodInterceptor,拦截方法

public class MethodParamInterceptor implements MethodInterceptor {

@Override

@SuppressWarnings("unchecked")

public Object invoke(MethodInvocation invocation) throws Throwable {

Object[] params = invocation.getArguments();

if (ArrayUtils.isEmpty(params)) {

return invocation.proceed();

}

for (Object param : params) {

//如果参数类型是Map

if (param instanceof Map) {

Map paramMap = (Map) param;

processPage(paramMap);

break;

}

}

return invocation.proceed();

}

/**

*

* @param paramMap

*/

private void processPage(Map paramMap) {

if (!paramMap.containsKey("page") && !paramMap.containsKey("limit")) {

return;

}

int page = 1;

int rows = 10;

for (Map.Entry entry : paramMap.entrySet()) {

String key = entry.getKey();

String value = entry.getValue().toString();

if ("page".equals(key)) {

page = NumberUtils.toInt(value, page);

} else if ("limit".equals(key)) {

rows = NumberUtils.toInt(value, rows);

}else {

//TODO

}

}

int offset = (page - 1) * rows;

paramMap.put("offset", offset);

paramMap.put("rows", rows);

}

}

2、定义后置处理器,将方法拦截件加入到advisor中。我们通过注解@Controller拦截所有的Controller,@RestController继承于Controller,所以统一拦截了。

public class RequestParamPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor

implements InitializingBean {

private Class validatedAnnotationType = Controller.class;

@Override

public void afterPropertiesSet() throws Exception {

Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true);

this.advisor = new DefaultPointcutAdvisor(pointcut, new MethodParamInterceptor());

}

}

3、万事俱备只欠东风,Processor也写好了,只需要让Processor生效。

@Configuration

public class MethodInterceptorConfig {

@Bean

public RequestParamPostProcessor converter() {

return new RequestParamPostProcessor();

}

}`

这里有个坑需要注意一下,如果在配置类中注入业务Bean。

@Configuration

public class MethodInterceptorConfig {

@Autowired

private UserService userService;

@Bean

public RequestParamPostProcessor converter() {

return new RequestParamPostProcessor();

}

}

启动时,会出现:

2019-11-08 14:55:50.954 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'sqlSessionFactory' of type [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2019-11-08 14:55:50.960 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'sqlSessionTemplate' of type [org.mybatis.spring.SqlSessionTemplate] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2019-11-08 14:55:51.109 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'rememberMapper' of type [com.sun.proxy.$Proxy84] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2019-11-08 14:55:53.406 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

很多切面失效,如事务切面。这是因为注入了自定义的Bean,自定义的Bean优先级最低,由最低优先级的BeanPostProcessor来加载并完成初始化的。但为了加载其中的RequestParamPostProcessor,导致不得不优先装载低优先级Bean,此时事务处理器的AOP等都还没完成加载,注解事务初始化都失败了。但Spring就提示了一个INFO级别的提示,然后剩下的Bean由最低优先级的BeanPostProcessor正常处理。

AspectJ方式实现切面

@Component@Aspect@Slf4jpublic class MethodParamInterceptor {

   @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
   public void paramAspect() {

   }


   @Before("paramAspect()")
   public void beforeDataSource(JoinPoint joinPoint) {
       Arrays.stream(joinPoint.getArgs()).forEach(paramObject -> {
           if (paramObject instanceof Map) {
               Map parameter = (Map) paramObject;
               processPage(parameter);
           }
       });

   }

   private void processPage(Map
  
    paramMap) {        
   if (null == paramMap) {            
   ret        }        
   if (!paramMap.containsKey(
   "page") && !paramMap.containsKey(
   "limit")) {            
   return;        }        int page = 1;        int rows = 10;        
   for (Map.Entry
   
     entry : paramMap.entrySet()) {            String key = entry.getKey();            String value = entry.getValue().toString();            
    if (
    "page".equals(key)) {                page = NumberUtils.toInt(value, page);            } 
    else 
    if (
    "limit".equals(key)) {                rows = NumberUtils.toInt(value, rows);            }        }        int offset = (page - 1) * rows;        paramMap.put(
    "offset", offset);        paramMap.put(
    "rows", rows);    }    @After(
    "paramAspect()")    public void afterDataSource(JoinPoint joinPoint) {    } } 
   
  

从上面两个例子可以对比出SpringAOP和AspectJ的两种不同用法,但达到的能力是一样的。

Sping AOP在组织、抽象代码场景中更加适合,AspectJ用于单纯的切面来实现某项功能更加简洁。

原创文章,作者:晴川运维,如若转载,请注明出处:https://baike.qcidc.com/10789.html

(0)
晴川运维晴川运维
上一篇 11小时前
下一篇 11小时前

相关推荐

  • Go语言中常用的开发神器

    Go语言(或 Golang)起源于 2007 年,并在 2009 年正式对外发布。Go 是非常年轻的一门语言,它的主要目标是“兼具 Python 等动态语言的开发速度和 C/C++…

    Linux系统 2025年6月8日
  • 详解python字典和结构化数据

    5.1 字典数据类型 字典的索引可以使用许多不同类型的数据,不只是整数。字典的索引被称为“键”,键及其关联的值称为“键—值”对,在代码中,字典输入时带花括号{}。 字典中的表项是不…

    Linux系统 2025年6月8日
  • Mariadb中聚合函数和分组函数具体使用方法

    聚合函数能对集合中的一组数据进行计算,并返回单个计算结果,分组函数通过一定的规则将一个数据集划分为若干个小的区域,然后针对若干个小区域进行统计汇总,般用于对查询结果分组统计,常与聚…

    Linux系统 2025年6月13日
  • 远程连接Linux服务器具体方法

    如何远程连接linux服务器?作为一款服务器级别的操作系统,linux充分考虑了远程登录的问题,无论是从linux、windows还是其他一些操作系统登录到linux都是非常方便的…

    Linux系统 2025年6月8日
  • Linux中安装和使用Cpufetch

    Cpufetch是一款功能强大的CPU架构信息获取工具,该工具支持x86、x86_64(Intel和AMD)以及ARM架构的CPU。Cpufetch支持在Linux、Windows…

    Linux系统 2025年6月8日
  • Linux中使用TCP 封装器加强网络服务安全

    在这篇文章中,我们将会讲述什么是 TCP 封装器TCP wrappers以及如何在一台 Linux 服务器上配置他们来限制网络服务的权限。在开始之前,我们必须澄清 TCP 封装器并…

    Linux系统 2025年6月11日
  • Linux下使用JMeter进行压力测试

    JMeter是Apache组织的开放源代码项目,它是功能和性能测试的工具,100%的用java实现,本篇文章重点为大家讲解一下Linux下运行JMeter具体方法。 准备工作 1.…

    Linux系统 2025年6月8日
  • 详解TCP长连接和短连接

    HTTP的长连接和短连接本质上是TCP长连接和短连接。HTTP属于应用层协议,在传输层使用TCP协议,在网络层使用IP协议。IP协议主要解决网络路由和寻址问题,TCP协议主要解决如…

    Linux系统 2025年6月8日
  • 详解Redis集群快捷迁移工具:Redis-migrate-tool

    Redis-Migrate-Tool(都简称RMT),是唯品会开源的redis数据迁移工具,主要用于异构redis集群间的数据在线迁移,即数据迁移过程中源集群仍可以正常接受业务读写…

    Linux系统 2025年6月18日
  • 浅谈Base64编码原理

    Base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于 2的6次方是64,所以每6个比特为一个单元,对应某个可打印字符。3个字节有24个比特,对应于4个Base64…

    Linux系统 2025年6月17日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注