001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.shiro.spring.aop;
020
021import org.apache.shiro.aop.AnnotationResolver;
022import org.apache.shiro.aop.MethodInvocation;
023import org.springframework.core.annotation.AnnotationUtils;
024import org.springframework.util.ClassUtils;
025
026import java.lang.annotation.Annotation;
027import java.lang.reflect.Method;
028
029/**
030 * {@code AnnotationResolver} implementation that uses Spring's more robust
031 * {@link AnnotationUtils AnnotationUtils} to find method annotations instead of the JDKs simpler
032 * (and rather lacking) {@link Method}.{@link Method#getAnnotation(Class) getAnnotation(class)}
033 * implementation.
034 *
035 * @since 1.1
036 */
037public class SpringAnnotationResolver implements AnnotationResolver {
038
039    public Annotation getAnnotation(MethodInvocation mi, Class<? extends Annotation> clazz) {
040        Method m = mi.getMethod();
041
042        Annotation a = AnnotationUtils.findAnnotation(m, clazz);
043        if (a != null) return a;
044
045        //The MethodInvocation's method object could be a method defined in an interface.
046        //However, if the annotation existed in the interface's implementation (and not
047        //the interface itself), it won't be on the above method object.  Instead, we need to
048        //acquire the method representation from the targetClass and check directly on the
049        //implementation itself:
050        Class<?> targetClass = mi.getThis().getClass();
051        m = ClassUtils.getMostSpecificMethod(m, targetClass);
052        a = AnnotationUtils.findAnnotation(m, clazz);
053        if (a != null) return a;
054        // See if the class has the same annotation
055        return AnnotationUtils.findAnnotation(mi.getThis().getClass(), clazz);
056    }
057}