有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringAOP可以访问目标值和注释值

在我当前的设置中,我需要访问方法的注释值和目标类本身(或者更准确地说,是它的一部分)

以下是我目前正在做的事情:

@Around("@annotation(CustomAnnotation) && target(myInterface)")
public Object interruptIfEmptyExtensionOrNoConnectorFound(
    ProceedingJoinPoint proceedingJoinPoint,
    MyInterface myInterface) throws Throwable {
        ...
}

注释带有一个整数值,指定一个参数(位置),用于对&;MyInterface包含更多(非静态)验证信息

如果我将注释添加到此方法签名,我将得到

java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut 

一旦Spring尝试加载ApplicationContext。如果我尝试更改通知中的参数顺序和/或从切入点删除“target()”条目,也会发生同样的情况。 (此加载当前采用SpringJUnit4ClassRunner的形式,在应用程序上下文文件中将实现接口的方面和类作为bean

当然,我可以通过proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(...).getAnnotations()获得注释的值,并为每个ing获得一些值,但是使用这种方法会在一个6行长的参数验证方法中添加10-15行,并且感觉。。。错

我认为,如果“target”类也在advice方法签名中,那么类似presentedhere的东西是可能的,但似乎我错了或理解错了

以下是获取注释的非工作尝试:

 @Around("@annotation(CustomAnnotation) && target(myInterface)")
    public Object interruptIfEmptyExtensionOrNoConnectorFound(
        ProceedingJoinPoint proceedingJoinPoint,
        CustomAnnotation customAnnotation,
        MyInterface myInterface) throws Throwable {
            ...
    }

 @Around("@annotation(CustomAnnotation) && target(myInterface)")
        public Object interruptIfEmptyExtensionOrNoConnectorFound(
            ProceedingJoinPoint proceedingJoinPoint,
            MyInterface myInterface,
            CustomAnnotation customAnnotation,) throws Throwable {
                ...
        }

这就是我当前检索注释的方式:

MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = methodSignature.getMethod();
if (method.getDeclaringClass().isInterface()) {
    method = proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(proceedingJoinPoint.getSignature().getName(), method.getParameterTypes());
}

CustomAnnotation customAnnotation = null;
for (Annotation annotation : method.getAnnotations()) {
    if (annotation.annotationType().equals(RequiresConnector.class)) {
        customAnnotation = (CustomAnnotation) annotation;
    }
}
return customAnnotation;

共 (0) 个答案