什么是AOP思想?

AOP思想目的是为了提高代码的模块化程度,不修改现有代码的基础上动态的去执行和变化代码中的逻辑。

全称为:面向切面编程(Aspect Oriented Programming), 而在想要扩展新功能的位置,称为**"切入点",** 新功能业务逻辑代码称为**"切面"。**

和动态代理是不是非常像,其实就是基于动态代理技术实现的,在运行是创建切入点的代理对象,这些代理对象会来拦截原本切入点对象的方法的调用,并在方法执行前后执行切面的逻辑。

@Aspect 是一个独立的AOP框架,spring对他做了支持,

@EnableAspectJAutoProxy注解启用了对这个框架的支持

概念:


几种场景:

权限校验拦截器:

实际上spring的拦截器底层就是利用AOP思想来实现的

简答代码展示:

Aspect类说明了变化的代码逻辑:

java 复制代码
@Aspect
@Component
@Order(-1)
public class NameAspect {

    private static final Logger logger = LoggerFactory.getLogger(NameAspect.class);

    @Pointcut("@annotation(com.openapi.weekcode.annotation.name)")
    public void start(){

    }

    @Before("@annotation(name)")
    public void before(JoinPoint joinPoint, name name){
        String myname = name.value();
        logger.info("Hi, my name is " + myname);

    }
    @After("@annotation(name)")
    public void after(JoinPoint joinPoint, name name){
        String myname = name.value();
        logger.info("Bye, my name is " + myname);
    }
    @AfterReturning(value = "@annotation(name)",returning = "result")
    public void afterReturning(JoinPoint joinPoint, name name, Object result){
        if (result instanceof Response){
            Response<String> response = (Response<String>) result;
            response.setData("Modified function!");
        }
    }
}

注解类:

java 复制代码
package com.openapi.weekcode.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface name {
    String value() default "";
}

简单的controller代码:

java 复制代码
    @name(value = "junhqin")
    @PostMapping("/list")
    public Response list(){
        Response<String> response = new Response<>("original function!");
        return response;
    }

结果:


思考

对于一个框架最重要的是如何满足快速搭建业务功能的需求,因此springboot的量大特性:IOC和AOP正好满足"业务功能拓展"和"性能消耗管理"。

相关推荐
艾菜籽15 小时前
Spring Web MVC入门补充1
java·后端·spring·mvc
失散1315 小时前
分布式专题——44 ElasticSearch安装
java·分布式·elasticsearch·架构
无限进步_15 小时前
扫雷游戏的设计与实现:扫雷游戏3.0
c语言·开发语言·c++·后端·算法·游戏·游戏程序
qq_4335545415 小时前
C++ 完全背包
开发语言·c++·算法
青铜弟弟15 小时前
R语言利用Export包导出pptx格式的文件有错误的原因
开发语言·r语言
MicrosoftReactor16 小时前
技术速递|使用 GitHub Copilot Agent 模式现代化 Java 项目的分步指南
java·github·copilot
Siren_dream16 小时前
python进阶_Day8
开发语言·python
蓝天智能16 小时前
QT QML交互原理:信号与槽机制
开发语言·qt·交互
ahauedu16 小时前
Spring Boot 2.7+ 中 RedisConnectionFactory Autowire 警告的深度解析
java·spring boot·后端