Eri*_*rik 13 aop spring spring-aop
考虑我已经定义了以下方面:
@Aspect
public class SampleAspect {
@Around(value="@annotation(sample.SampleAnnotation)")
public Object display(ProceedingJoinPoint joinPoint) throws Throwable {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
和注释
public @interface SampleAnnotation {
String value() default "defaultValue";
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在display方法中读取显示方法中注释SampleAnnotation的value参数?
谢谢你的帮助,erik
Dav*_*itz 19
将建议签名更改为
@Around(value="@annotation(sampleAnnotation)")
public Object display(ProceedingJoinPoint joinPoint, SampleAnnotation sampleAnnotation ) throws Throwable {
// ...
}
Run Code Online (Sandbox Code Playgroud)
并且您可以访问注释中的值.
有关详细信息,请参阅文档.
下面我将添加一个完整的 AOP 实现示例,我将从我的自定义 pointCut 注释中获取参数,我的建议旨在计算函数的执行时间:
1-自定义注释:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationLogExecutionTime {
public boolean isActivate() default false;
}
Run Code Online (Sandbox Code Playgroud)
2-控制器:
@AnnotationLogExecutionTime(isActivate = true)
@PostMapping("/connection")
public HttpEntity<String> createAuthenticationToken(HttpServletRequest request,
@RequestBody AuthenticationRequest authenticationRequest) {...}
Run Code Online (Sandbox Code Playgroud)
3- 建议
@Component
@Aspect
public class LoggingExecutionTimeAdvice {
@Around("@annotation(annotationLogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint, AnnotationLogExecutionTime annotationLogExecutionTime) throws Throwable {
if(annotationLogExecutionTime.isActivate()){//Here I recover the value!!!!
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed;
}
Object proceed = joinPoint.proceed();
return proceed;
}
}
Run Code Online (Sandbox Code Playgroud)
解释:
我们的建议 (logExecutionTime)将围绕 (joinPoint)执行,该函数将使用 AnnotationLogExecutionTime(我们的自定义注释)进行注释,因此我想激活或不激活时间执行的计算,因此我将从我们的成员中获取值自定义注释(您询问;))
归档时间: |
|
查看次数: |
13340 次 |
最近记录: |