Spring引导方面是否在预定方法内的方法上工作

问题描述 投票:0回答:1

适用于春季启动应用。

我的方面在我的预定方法中监听我的私有或公共方法。

但它不起作用。但是,该方面可以监听我的预定方法。

这是我的github上的一个例子。

https://github.com/benweizhu/spring-boot-aspect-scheduled

有没有人知道答案或为什么?或者如何解决?

谢谢

spring aspect spring-scheduled
1个回答
1
投票

Aspects不能在同一个类中调用其他方法,因为它们无法代理。

这意味着自我调用不会导致与方法调用相关的建议有机会执行。

好的,那么该怎么办呢?最好的方法(这里松散地使用最好的术语)是重构你的代码,这样就不会发生自我调用

关于代理私有方法的说明:

由于Spring的AOP框架基于代理的特性,受保护的方法根据定义不会被拦截,既不用于JDK代理(这不适用),也不用于CGLIB代理(这在技术上可行,但不建议用于AOP)。因此,任何给定的切入点都只能与公共方法匹配!

如果您的拦截需要包括受保护/私有方法甚至构造函数,请考虑使用Spring驱动的本机AspectJ编织而不是Spring的基于代理的AOP框架。这构成了具有不同特征的不同AOP使用模式,因此在做出决定之前一定要先熟悉编织。

参考:How can I log private methods via Spring AOP?

更改代码如下:

@Component
public  class Test{

    public void reportInPrivateMethod() {
        System.out.println("private method");

    }

    public void reportInPublicMethod() {
        System.out.println("public method");

    }
}

现在调用此方法:

@Component
public class ScheduledTasks {

    @Autowired
    private Test test;

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        test.reportInPrivateMethod();
        test.reportInPublicMethod();
        log.info("The time is now {}", dateFormat.format(new Date()));
    }


}

根据更改修改方面:

@Aspect
@Component
public class Monitor {

   @AfterReturning("execution(* com.zeph.aop.ScheduledTasks.reportCurrentTime())")
public void logServiceAccess(JoinPoint joinPoint) {
    System.out.println("Completed: " + joinPoint);
}

@AfterReturning("execution(* com.zeph.aop.Test.reportInPrivateMethod())")
public void logServiceAccessPrivateMethod() {
    System.out.println("Completed  PRIVATE :");
}

@AfterReturning("execution(* com.zeph.aop.Test.reportInPublicMethod())")
public void logServiceAccessPublicMethod() {
    System.out.println("Completed PUBLIC: ");
}
}
© www.soinside.com 2019 - 2024. All rights reserved.