【问题标题】:Configure Pointcut for Spring JPA repository methods为 Spring JPA 存储库方法配置切入点
【发布时间】:2019-10-15 10:22:51
【问题描述】:

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

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 存储库方法之后运行?

【问题讨论】:

    标签: java spring spring-aop


    【解决方案1】:

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

    类似的东西

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

    或者让它更通用

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

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

    【讨论】:

    • 我尝试在 ProcessDao 中添加 save 方法以及在 save Pointcut 中添加参数。它不起作用,但我使用的正则表达式不同,我现在将尝试使用这个正则表达式。
    • 它不是一个正则表达式,而是一个用 AspectJ 切入点语言编写的切入点表达式。也可以代替 * yuo 使用 .. (表示 0 个或多个参数)。
    • Pointcut 表达式有效,我也没有在 ProcessDao 中添加保存方法。感谢您的帮助:)
    • 对此的跟进,JPARepository 具有 save() ,它可以获取列表以及单个对象。如何为这些情况实现两个不同的切入点表达式?
    • 这是一个不同的问题,我不想在评论中回答,因为有几种方法。
    猜你喜欢
    • 2017-08-20
    • 2019-10-04
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2017-01-06
    相关资源
    最近更新 更多