spring-boot - 如何在 Spring 增删改查存储库方法上实现 Aspect

标签 spring-boot spring-data-jpa aspectj

我正在做一个项目,其中我们有很多实体,我们将对其进行 CRUD 操作。我创建了一个基本实体类,并且在所有其他实体中我扩展了基本实体类,该类具有公共(public)字段,如created_date、created_by、last_updated_date、last_updated_by 等。现在,我想在 Spring CrudRepository 方法上实现方面并设置上述内容保存时提到的字段。

我尝试过实现类似的东西,但不起作用。

package com.cerium.aop;

import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cerium.datamodel.AccountDataModel;
import com.cerium.domain.Account;
import com.cerium.domain.BaseEntity;
import com.cerium.util.Constants;

/**
 * @author Manikanta B Cerium
 *
 */
@Component
@Aspect
public class SampleAspect {

    private static final Logger LOG = LoggerFactory.getLogger(SampleAspect.class);

    @Around("execution(* com.cerium.repository.*.save (com.cerium.domain.BaseEntity)) && args(saveData)")
    public Object beforeSave(ProceedingJoinPoint proceedingJoinPoint, Object saveData) throws Throwable {

        LOG.debug("Into aspect before save: {}", saveData);

        BaseEntity baseEntity = (BaseEntity) proceedingJoinPoint.proceed(new Object[] { saveData });

        // set the fields here......
        baseEntity.setCreatedDate(new Date());

        System.out.println(saveData);

        return baseEntity;

    }
}

最佳答案

要使用方面,我们应该首先使用过滤器表达式定义一个切入点方法(在您的情况下为“保存”方法),然后创建一个方法来处理此切入点:

@Component
@Aspect
public class CommonSaveAspect {

    @Pointcut("execution(* com.cerium.repository.*.save(..))")
    public void commonSave() {
    }

    @Around("commonSave()")
    public Object addCommonData(final ProceedingJoinPoint pjp) throws Throwable {

        Object[] args = pjp.getArgs();

        if (Iterable.class.isAssignableFrom(args[0].getClass())) {
            //noinspection unchecked
            Iterable<BaseEntity> entities = (Iterable<BaseEntity>) args[0];
            entities.forEach(entity -> {
                // set the fields here...
            });
        }

        if (args[0] instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) args[0];
            // set the fields here...
        }

        return pjp.proceed(args); 
    }
}

More info

关于spring-boot - 如何在 Spring 增删改查存储库方法上实现 Aspect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041594/

相关文章:

spring-boot - spring-boot添加Redis(spring-boot-starter-data-redis)依赖后报错

java - AspectJ/使用编译时反射生成方法

aspectj - Kotlin 中是否有任何方法可以像 Java 中的 AspectJ 那样在函数之前/之后/周围编织代码?

java - com.springboot.todoController.TodoController 中的字段 todoService 需要类型为 'com.springboot.todo.TodoService' 的 bean,但无法找到

java - @IfProfileValue 两个 Spring 轮廓

java - java中将mysql表中的字符串数据转换为json列表

hibernate - 带有非键连接列的 Spring boot 多对一不起作用

mysql - 如何加速 max(...) 查询