带注释的私有方法的 AspectJ 切入点 [英] AspectJ pointcut for annotated PRIVATE methods

查看:44
本文介绍了带注释的私有方法的 AspectJ 切入点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为使用特定注释进行注释的私有方法创建切入点.但是,当注释位于如下私有方法上时,不会触发我的方面.

I want to create a Pointcut for private methods that are annotated with a specific annotation. However my aspect is not triggered when the annotation is on a private method like below.

@Aspect
public class ServiceValidatorAspect {
    @Pointcut("within(@com.example.ValidatorMethod *)")
    public void methodsAnnotatedWithValidated() {
}

@AfterReturning(
            pointcut = "methodsAnnotatedWithValidated()",
            returning = "result")
    public void throwExceptionIfErrorExists(JoinPoint joinPoint, Object result) {
         ...
}

服务接口

public interface UserService {

    UserDto createUser(UserDto userDto);
}

服务实施

    public class UserServiceImpl implements UserService {

       public UserDto createUser(UserDto userDto) {

             validateUser(userDto);

             userDao.create(userDto);
       }

       @ValidatorMethod
       private validateUser(UserDto userDto) {

            // code here
       }

但是,如果我将注释移动到公共接口方法实现 createUser,我的方面就会被触发.我应该如何定义我的切入点或配置我的方面以使我的原始用例工作?

However if I move the annotation to a public interface method implementation createUser, my aspect is triggered. How should I define my pointcut or configure my aspect to get my original use case working?

推荐答案

8.使用 Spring 进行面向方面的编程

由于 Spring 的 AOP 框架基于代理的特性,根据定义,受保护的方法不会被拦截,对于 JDK 代理(这不适用)和 CGLIB 代理(这在技术上是可行的,但不推荐用于 AOP)目的).因此,任何给定的切入点都将仅与公共方法匹配!

Due to the proxy-based nature of Spring's AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn't applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!

如果你的拦截需要包括protected/private方法甚至构造函数,可以考虑使用Spring驱动的原生AspectJ织入,而不是Spring的基于代理的AOP框架.这构成了不同特点的不同AOP使用模式,所以一定要先熟悉织法再做决定.

If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring's proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision.

这篇关于带注释的私有方法的 AspectJ 切入点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆