spring aop的概念与实战以及面试项目题

aop为面向切面编程,面向方向编程。

在Spring aop 可以简单理解为面向方法编程。

在不修改目标方法源代码的前提下,与业务无关,但对多个对象产生影响的公共行为和逻辑,抽取公共模块复用,降低耦合。

Spring AOP底层通过动态代理机制实现对目标方法的编程,动态代理是目前面向方法编程最主流的编程。

其他:比如:给目标方法添加事务管理,给目标方法添加访问权限控制。对目标方法进行读写分类。

面试题:什么是aop,你在项目中有没有用到aop?

在Spring aop 可以简单理解为面向方法编程。

在不修改目标方法源代码的前提下,与业务无关,但对多个对象产生影响的公共行为和逻辑,抽取公共模块复用,降低耦合。

答:我在项目中有很多地方用到了aop编程,我在校园零食店的项目中,在实现插入零食和更新零食接口时,我需要给数据库插入创建时间,更新时间,创建人,更新人,这些公共字段。代码过于隆余,耦合性较高。于是,我就自定义了一个注解,用枚举存放更新和插入标识。 然后使用aop切面,通过在方法执行之前,通过反射获取获取注解上的value值和实体对象,判断更新或者插入标识的不同,根据当前实体对象通过反射用set方法为公共字段去赋值。提高了公共模块服用,降低耦和。

例外,spring中的事务本质上也是通过aop功能,对方法前后进行拦截,在执行方法前开启事务,在执行完目标后提交或者回滚事务。

下面代码演示:

java 复制代码
@Target({ElementType.METHOD})
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface AutoFill {
    // 数据库操作类型:插入、更新 update insert
    OperationType value();
}
java 复制代码
package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

import static org.apache.ibatis.ognl.OgnlRuntime.setFieldValue;

/**
 * 自定义切面,实现自动填充功能
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 切入点
     *
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {}
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始自动填充切点");
        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();//方法签名对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获取方法上的注解对象
        OperationType operationType = autoFill.value();
        //获取当前被拦截的方法上的参数--实体对象
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0)
            return;
        //准备赋值的数据
        Object entity = args[0];
        LocalDateTime now= LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //根据当前不同的操作类型,为对应的属性通过反射来赋值
        if(operationType == OperationType.INSERT) {
            //为四个公共字段来赋值
            Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            //通过反射为对象属性赋值
            setCreateTime.invoke(entity,now);
            setCreateUser.invoke(entity,currentId);
            setUpdateTime.invoke(entity,now);
            setUpdateUser.invoke(entity,currentId);
        }else if(operationType == OperationType.UPDATE) {
            Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateTime.invoke(entity,now);
            setUpdateUser.invoke(entity,currentId);
        }

        }




    }
相关推荐
pshdhx_albert1 小时前
AI agent实现打字机效果
java·http·ai编程
沉鱼.441 小时前
第十二届题目
java·前端·算法
Accerlator2 小时前
2026 年 4 月 1 日电话面试
面试·职场和发展
赫瑞2 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构
周末也要写八哥3 小时前
多进程和多线程的特点和区别
java·开发语言·jvm
惜茶4 小时前
vue+SpringBoot(前后端交互)
java·vue.js·spring boot
杰克尼5 小时前
springCloud_day07(MQ高级)
java·spring·spring cloud
前端Hardy6 小时前
前端必看!LocalStorage这么用,再也不踩坑(多框架通用,直接复制)
前端·javascript·面试
前端Hardy6 小时前
前端必看!前端路由守卫这么写,再也不担心权限混乱(Vue/React通用)
前端·javascript·面试
NHuan^_^6 小时前
SpringBoot3 整合 SpringAI 实现ai助手(记忆)
java·人工智能·spring boot