spring - 带注释的 PRIVATE 方法的 AspectJ 切入点

标签 spring aop aspectj spring-aop

我想为带有特定注释的私有(private)方法创建一个切入点。但是,当注释位于下面的私有(private)方法上时,不会触发我的方面。

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

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

服务接口(interface)
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
       }

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

最佳答案

8. Aspect Oriented Programming with Spring

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!

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.

关于spring - 带注释的 PRIVATE 方法的 AspectJ 切入点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15093894/

相关文章:

java - Color HttpMessageConverter 但缺少 Color 的默认构造函数

java - Spring Boot 国际化(messages.properties)

java - Spring AOP : Around aspect not working

java - 注释为的类或子类的方面

java - 编译时自动添加未实现的方法

java - Spring Batch 中的复制作业

java - 如何将硬编码的 SQL 查询传递到 JdbcBatchItemWriter 中?

java - 在 Java 中使用面向方面的编程和注释标记的方法

java - spectj 将对象获取到切入点内

java - 如何继承/替换java的final类?