man*_*gel 1 spring annotations aspect
Spring 和 AOP 编程新手。致力于 Spring AOP 教程,编写拦截方法调用的方面。想要启用时间记录。
\n\n按照教程的指示,我创建了一个用于日志记录的自定义注释和一个方面来定义调用此注释时应执行的操作。\n下面的代码是 TrackTime 注释:
\n\npackage com.in28minutes.springboot.tutorial.basics.example.aop;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n@Target(ElementType.METHOD)\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface TrackTime {}\nRun Code Online (Sandbox Code Playgroud)\n\n但是 Eclipse 显示错误 \xe2\x80\x93\n\xe2\x80\x9cElement 无法解析为变量/保留无法解析为变量\xe2\x80\x9d
\n\n然后,我使用 \xe2\x80\x98TrackTime\xe2\x80\x99 注释创建了一个名为 MethodExecutionCalculationAspect 的方面。
\n\n@Around("@annotation(com.in28minutes.springboot.tutorial.\nbasics.example.aop.TrackTime)")\nRun Code Online (Sandbox Code Playgroud)\n\n方法执行计算方面
\n\npackage com.in28minutes.springboot.tutorial.basics.example.aop;\n\nimport org.aspectj.lang.ProceedingJoinPoint;\nimport org.aspectj.lang.annotation.Around;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Configuration;\n\n@Aspect\n@Configuration\npublic class MethodExecutionCalculationAspect {\n private Logger logger = LoggerFactory.getLogger(this.getClass());\n\n@Around("@annotation\n(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime)")\n\n public void around(ProceedingJoinPoint joinPoint) throws Throwable {\n long startTime = System.currentTimeMillis();\n\n joinPoint.proceed();\n long timeTaken = System.currentTimeMillis() - startTime;\n logger.info("Time Taken by {} is {}", joinPoint, timeTaken);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n}
\n\n@Around 使用周围建议。它拦截方法调用并使用 joinPoint.proceed() 来执行该方法。\n @annotation(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime) 是基于注释定义拦截的切入点 \xe2 \x80\x94 @annotation \n后跟注释的完整类型名称。
\n\n一旦我更正注释和建议,我\xe2\x80\x99m希望在方法上使用注释来进行时间跟踪。如下所示:
\n\n@Service\npublic class Business1 {\n @TrackTime\n public String calculateSomething(){\nRun Code Online (Sandbox Code Playgroud)\n\n任何帮助,将不胜感激。
\n\n该项目信息如下:
\n\nSpringBootTutorialBasicsAplication.java:\n使用 Spring Initializer 生成的 Spring Boot 应用程序类。此类充当应用程序的启动点。
\n\n\xe2\x80\xa2 pom.xml:包含使用 Spring Boot Starter AOP 构建此项目所需的所有依赖项。
\n\n\xe2\x80\xa2 Business1.java、Business2.java、Dao1.java、Dao2.java:业务类依赖于 DAO 类。
\n\n\xe2\x80\xa2 我们将编写方面来拦截对这些业务和 DAO 类的调用。
\n\n\xe2\x80\xa2 AfterAopAspect.java:实现一些 After 建议。
\n\n\xe2\x80\xa2 UserAccessAspect.java:实现 Before 建议来执行访问检查。
\n\n\xe2\x80\xa2 BusinessAopSpringBootTest.java:调用业务方法的单元测试。
\n\n\xe2\x80\xa2 Maven 3.0+ 是您的构建工具\n\xe2\x80\xa2 Eclipse。\n\xe2\x80\xa2 JDK 1.8+
\n您TrackTime缺少RetentionPolicy和的导入Target。
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3879 次 |
| 最近记录: |