我一直在试图弄清楚为什么我的简单方面没有被执行。我查看了类似问题的答案,但仍然无法正常工作。
我的意图是使用 AOP 建议来包装使用自定义注释注释的方法的执行,该建议将跟踪方法运行所需的时间。当我运行测试时,我看到了该方法的输出,但没有运行建议(我希望它记录一些输出)。
这是 Aspect 类:
@Aspect
class LatencyProfiler {
private LatencyTrackerFactory factory = LatencyTrackerFactory.NOOP;
@Pointcut(value="execution(@ProfileLatency * *(..)) && @annotation(annotation)", argNames="annotation")
public void profiled(ProfileLatency annotation) {}
@Around(value="profiled(annotation)", argNames="pjp,annotation")
public Object profile(ProceedingJoinPoint pjp, ProfileLatency annotation) throws Throwable {
ILatencyTracker tracker;
try {
tracker = factory.create(annotation.trackerName(), annotation.trackerNameSuffix());
} catch (ConfigException e) {
throw new RuntimeException(e);
}
tracker.begin();
Object ret = pjp.proceed();
tracker.end(null);
return ret;
}
@Optional
public void setFactory(LatencyTrackerFactory factory) {
this.factory = factory;
}
}
紧随其后的是注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProfileLatency {
String trackerName();
String trackerNameSuffix() default"[unassigned]";
}
接下来是一个测试类:
public class Test {
private static final Log LOG = LogFactory.getLog(Test.class);
@PostConstruct
public void init() {
Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 60; i++) {
foo();
LOG.info("HERE");
}
}
}, 2000, TimeUnit.MILLISECONDS);
}
@ProfileLatency(trackerName = "latency", trackerNameSuffix = "s")
public void foo() {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}
弹簧配置:
<context:annotation-config/>
<aop:aspectj-autoproxy>
<aop:include name="latencyProfileAspect"/>
</aop:aspectj-autoproxy>
<bean
id = "latencyLogger"
class = "util.logging.LatencyLogger"
/>
<bean
id = "trackerFactory"
class = "util.latency.LatencyTrackerFactoryImpl">
<constructor-arg value = "config/latency-config.xml"/>
<constructor-arg ref = "latencyLogger"/>
</bean>
<bean
id = "latencyProfileAspect"
class = "util.latency.aop.LatencyProfiler"
p:factory-ref = "trackerFactory"
/>
<bean id = "test" class="util.Test"/>
最后是测试的输出:
21:20:37,930 INFO main/SpringMain - Ready.
21:20:40,928 INFO pool-4-thread-1/Test - HERE
21:20:41,927 INFO pool-4-thread-1/Test - HERE
21:20:42,926 INFO pool-4-thread-1/Test - HERE
21:20:43,925 INFO pool-4-thread-1/Test - HERE
21:20:44,924 INFO pool-4-thread-1/Test - HERE
...
任何意见是极大的赞赏。