Skip to content

Commit 454bb6e

Browse files
committed
bugfix(aop/guice): add support for retrieving annotations from superclasses in DefaultAnnotationResolver
1 parent 3e4f9e1 commit 454bb6e

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

core/src/main/java/org/apache/shiro/aop/DefaultAnnotationResolver.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,20 @@ public Annotation getAnnotation(MethodInvocation mi, Class<? extends Annotation>
6363
if (annotation == null) {
6464
Object miThis = mi.getThis();
6565
//SHIRO-473 - miThis could be null for static methods, just return null
66-
annotation = miThis != null ? miThis.getClass().getAnnotation(clazz) : null;
66+
annotation = miThis != null ? getAnnotationFromClassHierarchy(miThis.getClass(), clazz) : null;
6767
}
6868
return annotation;
6969
}
70+
71+
private Annotation getAnnotationFromClassHierarchy(Class<?> targetClass, Class<? extends Annotation> clazz) {
72+
Class<?> current = targetClass;
73+
while (current != null) {
74+
Annotation annotation = current.getDeclaredAnnotation(clazz);
75+
if (annotation != null) {
76+
return annotation;
77+
}
78+
current = current.getSuperclass();
79+
}
80+
return null;
81+
}
7082
}

core/src/test/java/org/apache/shiro/aop/AnnotationResolverTest.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ public void operateThat() {
4242
}
4343
}
4444

45+
@SuppressWarnings("unused")
46+
@RequiresRoles("admin")
47+
private static class ParentFixture {
48+
public void operateParent() {
49+
}
50+
}
51+
52+
private static final class ChildFixture extends ParentFixture {
53+
}
54+
4555
DefaultAnnotationResolver annotationResolver = new DefaultAnnotationResolver();
4656

4757
@Test
@@ -64,6 +74,17 @@ void testAnnotationFoundFromMethod() throws SecurityException, NoSuchMethodExcep
6474
assertThat(annotationResolver.getAnnotation(methodInvocation, RequiresUser.class)).isNotNull();
6575
}
6676

77+
@Test
78+
void testAnnotationFoundFromSuperclass() throws SecurityException, NoSuchMethodException {
79+
ChildFixture childFixture = new ChildFixture();
80+
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
81+
Method method = ParentFixture.class.getDeclaredMethod("operateParent");
82+
expect(methodInvocation.getMethod()).andReturn(method);
83+
expect(methodInvocation.getThis()).andReturn(childFixture);
84+
replay(methodInvocation);
85+
assertThat(annotationResolver.getAnnotation(methodInvocation, RequiresRoles.class)).isNotNull();
86+
}
87+
6788
@Test
6889
void testNullMethodInvocation() throws SecurityException, NoSuchMethodException {
6990
MethodInvocation methodInvocation = createMock(MethodInvocation.class);

0 commit comments

Comments
 (0)