详解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)
晴川运维晴川运维
上一篇 2025年6月28日
下一篇 2025年6月28日

相关推荐

  • Shell脚本习题:MySQL分库分表备份

    脚本详细内容 [root@db02 scripts]# cat /server/scripts/Store_backup.sh  &nbsp…

    Linux系统 2025年6月8日
  • 快速上手Linux ptrace 的实现

    Ptrace 提供了一种父进程可以控制子进程运行,并可以检查和改变它的核心image。它主要用于实现断点调试。一个被跟踪的进程运行中,直到发生一个信号。则进程被中止,并且通知其父进…

    Linux系统 2025年6月12日
  • Oracle数据库基本使用方法

    Oracle数据库是目前世界上使用最为广泛的数据库管理系统,作为一个通用的数据库系统,它具有完整的数据管理功能;作为一个关系数据库,它是一个完备关系的产品;作为分布式数据库它实现了…

    Linux系统 2025年6月23日
  • 分享一下Linux运维小技巧

    Linux运维人员主要是对Linux下各种网络服务、应用系统、监控系统等进行自动化脚本开发的工作,并根据项目对系统进行性能优化,下面为大家分享一下Linux运维常用小技巧。 1、查…

    Linux系统 2025年6月12日
  • Linux memcache安装和配置(自启动)过程详解

    memcache 是一个高性能的分布式的内存对象缓存系统,通过在内存中维护一张统一的、巨大的 Hash 表,它能够用来存储各种格式的数据,包括图像、视频、文件及数据库检索的结果等。…

    Linux系统 2025年6月18日
  • Python中非常重要的5个特性

    Python 是近十年来兴起的编程语言,并且被证明是一种非常强大的语言。我用 Python 构建了很多应用程序,从交互式地图到区块链。 Python 是近十年来兴起的编程语言,并且…

    Linux系统 2025年6月14日
  • 快速上手Vue.js

    Vue.js是当下很火的一个JavaScript MVVM库,它是以数据驱动和组件化的思想构建的。相比于Angular.js,Vue.js提供了更加简洁、更易于理解的API,使得我…

    Linux系统 2025年7月9日
  • 通过eNSP实现静态NAT转换

    eNSP是图形化网络仿真平台,该平台通过对真实网络设备的仿真模拟。网络转换技术也叫做NAT技术,他的作用就是实现私网IP和公网IP 的转换来达到网络的互通 实验环境: pc:172…

    Linux系统 2025年6月4日
  • 可靠消息服务实现具体方案

    分布式事务往往是服务化的痛点,很多场景通过业务避免了分布式事务,但是还是存在一些场景必须依赖分布式事务,下面来讲讲如何处理分布式事务 一 常用解决方案 分布式事物解决方式有很多,网…

    Linux系统 2025年7月8日
  • Linux中通过 kill 和 killall管理进程

    在 Linux 中,每个程序和守护程序daemon都是一个“进程process”。 大多数进程代表一个正在运行的程序。而另外一些程序可以派生出其他进程,比如说它会侦听某些事件的发生…

    Linux系统 2025年6月8日

发表回复

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