1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 package org.apache.shiro.spring.aop; 20 21 import org.apache.shiro.aop.AnnotationResolver; 22 import org.apache.shiro.aop.MethodInvocation; 23 import org.springframework.core.annotation.AnnotationUtils; 24 import org.springframework.util.ClassUtils; 25 26 import java.lang.annotation.Annotation; 27 import java.lang.reflect.Method; 28 29 /** 30 * {@code AnnotationResolver} implementation that uses Spring's more robust 31 * {@link AnnotationUtils AnnotationUtils} to find method annotations instead of the JDKs simpler 32 * (and rather lacking) {@link Method}.{@link Method#getAnnotation(Class) getAnnotation(class)} 33 * implementation. 34 * 35 * @since 1.1 36 */ 37 public class SpringAnnotationResolver implements AnnotationResolver { 38 39 public Annotation getAnnotation(MethodInvocation mi, Class<? extends Annotation> clazz) { 40 Method m = mi.getMethod(); 41 42 Annotation a = AnnotationUtils.findAnnotation(m, clazz); 43 if (a != null) return a; 44 45 //The MethodInvocation's method object could be a method defined in an interface. 46 //However, if the annotation existed in the interface's implementation (and not 47 //the interface itself), it won't be on the above method object. Instead, we need to 48 //acquire the method representation from the targetClass and check directly on the 49 //implementation itself: 50 Class<?> targetClass = mi.getThis().getClass(); 51 m = ClassUtils.getMostSpecificMethod(m, targetClass); 52 a = AnnotationUtils.findAnnotation(m, clazz); 53 if (a != null) return a; 54 // See if the class has the same annotation 55 return AnnotationUtils.findAnnotation(mi.getThis().getClass(), clazz); 56 } 57 }