为 Spring 个 JPA 存储库方法配置切入点

Configure Pointcut for Spring JPA repository methods

我正在尝试创建一个方面,在每次调用 Spring JpaRepository 的 save() 之后 运行s。我将我的方面定义如下:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class ProcessAspect {

    @Autowired
    private ProcessService processService;

    @AfterReturning(value = "execution(* com.domain.control.repository.ProcessDao.save())))",
    returning = "result")
    private void propagateProcess(JoinPoint joinPoint, Object result) {
        log.info("Aspect is working, congratulations. Jointpoint {} , result {}", joinPoint, result.toString());
        Process process = (process) result;

       // do something on the object returned by save()
        processService.createOrUpdateProcess(process);
    }

}

我的仓库定义如下:

@Repository
public interface ProcessDao extends JpaRepository<Process, String>

如果我以这种方式配置,则该方面无法正常工作。

如何在通用 JPA 存储库方法之后将我的方面配置为 运行?

首先你的 ProcessDao 没有 save 方法,所以它不会匹配,其次你有一个没有参数的切入点 save 方法并且有没有这样的事。相反,您想在切入点中使用 Spring 数据存储库 类 之一并匹配 1 个参数。

像这样

execution(* org.springframework.data.jpa.repository.JpaRepository+.save(..))))

或者让它更通用

execution(* org.springframework.data.repository.CrudRepository+.save(..))))

这应该使您的切入点匹配。还有一个 saveAllsaveAndFlush,所以如果您还需要拦截它们,您可能想添加更多的切入点。