Java 带有方面参数的注释
我有一个可用于注释的方面:Java 带有方面参数的注释,java,spring,annotations,aop,aspectj,Java,Spring,Annotations,Aop,Aspectj,我有一个可用于注释的方面: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DumpToFile { } 以及连接点: @Aspect @Component public class DumpToFileAspect { @Around("@annotation(DumpToFile)") public Object logExecutionTime(Proceedi
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DumpToFile {
}
以及连接点:
@Aspect
@Component
public class DumpToFileAspect {
@Around("@annotation(DumpToFile)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
...
// I likte to read out a parameter from the annotation...
Object proceed = joinPoint.proceed();
...
return proceed;
}
}
我可以在具有@DumpToFile
的方法上成功使用该特性;但是,我想向注释传递一个参数,并在我的方面中检索它的值。例如,
@DumpToFile(fileName=“mydump”)
。有人能告诉我怎么做吗?将您的@更改为:
@Aspect
@Component
public class DumpToFileAspect {
@Around("@annotation(dumpToFileAspect)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint, DumpToFile dumpToFileAspect) throws Throwable {
...
// I likte to read out a parameter from the annotation...
String fileName = dumpToFileAspect.getFileName();
Object proceed = joinPoint.proceed();
...
return proceed;
}
}
您应该能够将注释接口传递给拦截器方法。不过我还没试过
Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DumpToFile {
String fileName() default "default value";
}
在垃圾方面-
@Aspect
@Component
public class DumpToFileAspect {
@Around("@annotation(dtf)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint, DumpToFile dtf) throws Throwable {
...
// I likte to read out a parameter from the annotation...
System.out.println(dtf.fileName); // will print "fileName"
Object proceed = joinPoint.proceed();
...
return proceed;
}
}
您可以使用以下选项:
@Around("@annotation(dumpFile)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint,DumpToFile dumpFile)
在@注释中
必须是转储文件
参数名
有关详细信息,请参见谢谢!然而,我得到了一个错误。IntelliJ已经用提示未绑定切入点参数dtf
将@标记为红色。如果启动应用程序,我会得到由以下原因引起的异常:java.lang.IllegalArgumentException:error at::0 formal unbound in pointcut in org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression
mm..对此不确定。您是否可以再次检查您是否正确导入了org.aspectj.lang.JoinPoint..import org.aspectj.lang.ProceedingJoinPoint代码>啊,我知道了。在您的示例中,它必须是@Around(“@annotation(dtf)”)
-也就是说,它必须匹配参数的名称,而不是类型。-如果你能解决这个问题,我会接受答案。我修复了@shakhawat的示例代码,以使OP能够接受答案。这里的问题与我在shakhawat
的答案中评论的问题相同,请尝试将它绑定到你的包中,比如:@Around(“execution(*com.your.package.*(..)&@annotation(DumpToFile)”)啊,我明白了。在您的示例中,它必须是@Around(“@annotation(dumpToFileAspect)”)
——也就是说,它必须匹配参数的名称,而不是类型。我会接受shakhawat的答案,因为它更完整。我还修复了这里的代码。伙计们,请在发布答案之前测试一下你们的代码,否则你们只是在激怒OP。事实上,这个答案是最新的,但在我修改其他人的代码之前第一个是正确的。如果我是OP,我会接受这个。