我正在尝试实现方法调用“之前”和“之后”的功能。
我尝试了 spring-aop,但它有 bug(我怀疑这是我的 java 应用程序中 groovy 的组合)。
我不想使用 java 反射。
我认为创建一个以函数作为参数的方法在这里不合适,因为这些函数已经存在于另一个类中。
这就是我正在尝试做的事情(这只是 Activity 的一部分,我还有 10 个这样的 Activity ):
long startTimeMetric = System.nanoTime()
Timer timer = meterRegistry.timer("item 1")
myObject.theActivity(mediaContainer)
timer.record(System.nanoTime() - startTimeMetric, TimeUnit.NANOSECONDS)
long startTimeMetric = System.nanoTime()
Timer timer = meterRegistry.timer("item 2")
myObject2.theActivity2(mediaContainer)
timer.record(System.nanoTime() - startTimeMetric, TimeUnit.NANOSECONDS)
如何使每个桶中重复的第一行、第二行和第四行自动且优雅?
先谢谢了。
编辑: 我提到的 aop 的问题是我突然得到空指针,而没有 aop 则没问题。 我是如何实现aop的?
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyMonitor{}
@Aspect
@Component
public class TimeMonitoringAspect {
@Autowired
MeterRegistry meterRegistry;
@Around("@annotation(com.path.to.MyMonitor)")
public void before(ProceedingJoinPoint joinPoint) throws Throwable {
long startTimeMetric = System.nanoTime();
String methodName = joinPoint.getSignature().getName();
Timer timer = meterRegistry.timer(methodName);
joinPoint.proceed();
timer.record(System.nanoTime() - startTimeMetric, TimeUnit.NANOSECONDS);
}
}
对于我想要测量时间的每个方法,我在方法之前注释了@MyMonitor,并且它在大多数情况下都有效,但在某些情况下,它给出了我提到的空指针。
最佳答案
就AOP而言,仍然可以通过以下方式实现。
Spring 提供了一种简单的 AOP 方法,在大多数情况下都会使用。
关于java - java中调用另一个方法时触发一个方法(或者没有aop怎么做aop),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57360910/