Element Cannot be Resolved as Variable error in a custom annotation for method interception

Element Cannot be Resolved as Variable error in a custom annotation for method interception

Spring 和 AOP 编程的新手。在编写 spring AOP 教程以编写拦截方法调用的方面。想要启用时间记录。

按照教程的指示,我创建了一个用于日志记录的自定义注释和一个方面来定义调用此注释时应执行的操作。 下面的代码是 TrackTime 注解:

package com.in28minutes.springboot.tutorial.basics.example.aop;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackTime {}

但是 Eclipse 正在显示错误 – “元素无法解析为 Variable/Retention 无法解析为变量”

然后我使用“TrackTime”注释创建了一个名为 MethodExecutionCalculationAspect 的方面。

@Around("@annotation(com.in28minutes.springboot.tutorial.
basics.example.aop.TrackTime)")

MethodExecutionCalculationAspect

package com.in28minutes.springboot.tutorial.basics.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

@Aspect
@Configuration
public class MethodExecutionCalculationAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("@annotation
(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime)")

    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

    joinPoint.proceed();
    long timeTaken = System.currentTimeMillis() - startTime;
    logger.info("Time Taken by {} is {}", joinPoint, timeTaken);
}

}

@Around 使用环绕通知。它拦截方法调用并使用 joinPoint.proceed() 来执行该方法。 @annotation(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime) 是基于注解定义拦截的切入点——@annotation 后跟注释的完整类型名称。

一旦我更正了注释和建议,我希望在方法上使用注释来进行时间跟踪。如下图:

@Service
public class Business1 {
    @TrackTime
    public String calculateSomething(){

如有任何帮助,我们将不胜感激。

项目信息如下:

SpringBootTutorialBasicsAplication.java: Spring 引导应用程序 class 使用 Spring 初始化程序生成。此 class 作为应用程序的启动点。

• pom.xml:包含使用 Spring Boot Starter AOP 构建此项目所需的所有依赖项。

• Business1.java、Business2.java、Dao1.java、Dao2.java:业务classes 依赖于DAO classes。

• 我们将编写方面来拦截对这些业务和 DAO classes 的调用。

• AfterAopAspect.java:实施一些 After 建议。

• UserAccessAspect.java:实施一个 Before 建议以进行访问检查。

• BusinessAopSpringBootTest.java:调用业务方法的单元测试。

• Maven 3.0+ 是您的构建工具 • 日食。 • JDK 1.8+

您的 TrackTime 缺少 RetentionPolicyTarget 的导入。

import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;