【发布时间】:2015-03-12 19:43:56
【问题描述】:
简而言之,我的问题是,如果注释的方法不是公共的,我的注释会被忽略,但如果同一类中的另一个方法被注释,它就会被识别。
我正在尝试编写注释来记录方法的执行时间,如this answer 中所述。
这是我的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime
{
}
我的方面:
@Component
@Aspect
public class LogTimeAspect
{
@Around(value = "@annotation(annotation)")
public Object logExecutionTime(final ProceedingJoinPoint joinPoint, final LogExecutionTime annotation) throws Throwable
{
final long startingTime = System.currentTimeMillis();
try
{
System.out.println("Starting timed method");
final Object retval = joinPoint.proceed();
return retval;
}
finally
{
System.out.println("Finished. Timed method " + joinPoint.toShortString() + " took: " + (System.currentTimeMillis() - startingTime) + "ms.");
}
}
}
我使用注解的班级:
@Component("classToBeAnnotated")
public class ClassToBeAnnotated {
@LogExecutionTime
public void operate() throws InterruptedException {
System.out.println("Performing operation");
Thread.sleep(1000);
}
}
还有测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/DefaultApplicationContext.xml" })
public class TestLauncher
{
@Autowired
private ClassToBeAnnotated classToBeAnnotated;
@Test
public void test() throws InterruptedException
{
classToBeAnnotated.operate();
}
}
如果我运行上面显示的代码,我会得到
Starting timed method
Performing operation
Finished. Timed method execution(operate) took: 1025ms.
到目前为止一切顺利。但是如果我从带有注释的方法中删除public
@LogExecutionTime
void operate() throws InterruptedException
注释被忽略,我得到:
Performing operation
没有错误,没有警告,只是没有运行。但是最让我印象深刻的是,如果我在同一个类中添加另一个方法,并将它公开并注释它,我会得到与初始条件相同的输出,即使那个额外的方法除了具有相同的注释之外,它不会以任何方式被调用或与原始版本相关。
@Component("classToBeAnnotated")
public class ClassToBeAnnotated {
@LogExecutionTime
public void someOtherMethod()
{
}
@LogExecutionTime
void operate() throws InterruptedException {
System.out.println("Performing operation");
Thread.sleep(1000);
}
}
输出:
Starting timed method
Performing operation
Finished. Timed method execution(operate) took: 1029ms.
有人可以解释为什么会这样吗?
【问题讨论】:
标签: java spring annotations aop