Example usage for org.springframework.core.annotation AnnotationUtils findAnnotation

List of usage examples for org.springframework.core.annotation AnnotationUtils findAnnotation

Introduction

In this page you can find the example usage for org.springframework.core.annotation AnnotationUtils findAnnotation.

Prototype

@Nullable
public static <A extends Annotation> A findAnnotation(Class<?> clazz, @Nullable Class<A> annotationType) 

Source Link

Document

Find a single Annotation of annotationType on the supplied Class , traversing its interfaces, annotations, and superclasses if the annotation is not directly present on the given class itself.

Usage

From source file:org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.java

@Override
public Object postProcess(Object bean, String beanName, Method method, List<Annotation> annotations) {
    if (this.beanAnnotationAware() && AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        try {//from w ww.j a v a 2  s  .  c om
            resolveTargetBeanFromMethodWithBeanAnnotation(method);
        } catch (NoSuchBeanDefinitionException e) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Skipping endpoint creation; " + e.getMessage()
                        + "; perhaps due to some '@Conditional' annotation.");
            }
            return null;
        }
    }

    List<Advice> adviceChain = extractAdviceChain(beanName, annotations);

    MessageHandler handler = createHandler(bean, method, annotations);

    if (!CollectionUtils.isEmpty(adviceChain) && handler instanceof AbstractReplyProducingMessageHandler) {
        ((AbstractReplyProducingMessageHandler) handler).setAdviceChain(adviceChain);
    }

    if (handler instanceof Orderable) {
        Order orderAnnotation = AnnotationUtils.findAnnotation(method, Order.class);
        if (orderAnnotation != null) {
            ((Orderable) handler).setOrder(orderAnnotation.value());
        }
    }
    if (handler instanceof AbstractMessageProducingHandler || handler instanceof AbstractMessageRouter) {
        String sendTimeout = MessagingAnnotationUtils.resolveAttribute(annotations, "sendTimeout",
                String.class);
        if (sendTimeout != null) {
            Long value = Long.valueOf(this.beanFactory.resolveEmbeddedValue(sendTimeout));
            if (handler instanceof AbstractMessageProducingHandler) {
                ((AbstractMessageProducingHandler) handler).setSendTimeout(value);
            } else {
                ((AbstractMessageRouter) handler).setSendTimeout(value);
            }
        }
    }

    boolean handlerExists = false;
    if (this.beanAnnotationAware() && AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        Object handlerBean = this.resolveTargetBeanFromMethodWithBeanAnnotation(method);
        handlerExists = handlerBean != null && handler == handlerBean;
    }

    if (!handlerExists) {
        String handlerBeanName = generateHandlerBeanName(beanName, method);
        this.beanFactory.registerSingleton(handlerBeanName, handler);
        handler = (MessageHandler) this.beanFactory.initializeBean(handler, handlerBeanName);
    }

    if (AnnotatedElementUtils.isAnnotated(method, IdempotentReceiver.class.getName())
            && !AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        String[] interceptors = AnnotationUtils.getAnnotation(method, IdempotentReceiver.class).value();
        for (String interceptor : interceptors) {
            DefaultBeanFactoryPointcutAdvisor advisor = new DefaultBeanFactoryPointcutAdvisor();
            advisor.setAdviceBeanName(interceptor);
            NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
            pointcut.setMappedName("handleMessage");
            advisor.setPointcut(pointcut);
            advisor.setBeanFactory(this.beanFactory);

            if (handler instanceof Advised) {
                ((Advised) handler).addAdvisor(advisor);
            } else {
                ProxyFactory proxyFactory = new ProxyFactory(handler);
                proxyFactory.addAdvisor(advisor);
                handler = (MessageHandler) proxyFactory.getProxy(this.beanFactory.getBeanClassLoader());
            }
        }
    }

    if (!CollectionUtils.isEmpty(adviceChain)) {
        for (Advice advice : adviceChain) {
            if (advice instanceof HandleMessageAdvice) {
                NameMatchMethodPointcutAdvisor handlerAdvice = new NameMatchMethodPointcutAdvisor(advice);
                handlerAdvice.addMethodName("handleMessage");
                if (handler instanceof Advised) {
                    ((Advised) handler).addAdvisor(handlerAdvice);
                } else {
                    ProxyFactory proxyFactory = new ProxyFactory(handler);
                    proxyFactory.addAdvisor(handlerAdvice);
                    handler = (MessageHandler) proxyFactory.getProxy(this.beanFactory.getBeanClassLoader());
                }
            }
        }
    }

    AbstractEndpoint endpoint = createEndpoint(handler, method, annotations);
    if (endpoint != null) {
        return endpoint;
    }
    return handler;
}

From source file:org.springframework.integration.handler.support.MessagingMethodInvokerHelper.java

private Map<String, Map<Class<?>, HandlerMethod>> findHandlerMethodsForTarget(final Object targetObject,
        final Class<? extends Annotation> annotationType, final String methodNameToUse,
        final boolean requiresReply) {

    Map<String, Map<Class<?>, HandlerMethod>> handlerMethods = new HashMap<>();

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<>();
    final Map<Class<?>, HandlerMethod> candidateMessageMethods = new HashMap<>();
    final Map<Class<?>, HandlerMethod> fallbackMethods = new HashMap<>();
    final Map<Class<?>, HandlerMethod> fallbackMessageMethods = new HashMap<>();
    final AtomicReference<Class<?>> ambiguousFallbackType = new AtomicReference<>();
    final AtomicReference<Class<?>> ambiguousFallbackMessageGenericType = new AtomicReference<>();
    final Class<?> targetClass = getTargetClass(targetObject);

    final String methodName;

    if (methodNameToUse == null) {
        if (Function.class.isAssignableFrom(targetClass)) {
            methodName = "apply";
        } else if (Consumer.class.isAssignableFrom(targetClass)) {
            methodName = "accept";
        } else {//  ww  w .ja  va  2s .  c  om
            methodName = null;
        }
    } else {
        methodName = methodNameToUse;
    }

    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, method1 -> {
        boolean matchesAnnotation = false;
        if (method1.isBridge()) {
            return;
        }
        if (isMethodDefinedOnObjectClass(method1)) {
            return;
        }
        if (method1.getDeclaringClass().equals(Proxy.class)) {
            return;
        }
        if (annotationType != null && AnnotationUtils.findAnnotation(method1, annotationType) != null) {
            matchesAnnotation = true;
        } else if (!Modifier.isPublic(method1.getModifiers())) {
            return;
        }
        if (requiresReply && void.class.equals(method1.getReturnType())) {
            return;
        }
        if (methodName != null && !methodName.equals(method1.getName())) {
            return;
        }
        if (methodName == null && ObjectUtils.containsElement(new String[] { "start", "stop", "isRunning" },
                method1.getName())) {
            return;
        }
        HandlerMethod handlerMethod1;
        try {
            method1 = AopUtils.selectInvocableMethod(method1,
                    org.springframework.util.ClassUtils.getUserClass(targetObject));
            InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory
                    .createInvocableHandlerMethod(targetObject, method1);
            handlerMethod1 = new HandlerMethod(invocableHandlerMethod, this.canProcessMessageList);
            checkSpelInvokerRequired(targetClass, method1, handlerMethod1);
        } catch (IneligibleMethodException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Method [" + method1 + "] is not eligible for Message handling " + e.getMessage()
                        + ".");
            }
            return;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Method [" + method1 + "] is not eligible for Message handling.", e);
            }
            return;
        }
        if (AnnotationUtils.getAnnotation(method1, Default.class) != null) {
            Assert.state(this.defaultHandlerMethod == null,
                    () -> "Only one method can be @Default, but there are more for: " + targetObject);
            this.defaultHandlerMethod = handlerMethod1;
        }
        Class<?> targetParameterType = handlerMethod1.getTargetParameterType();
        if (matchesAnnotation || annotationType == null) {
            if (handlerMethod1.isMessageMethod()) {
                if (candidateMessageMethods.containsKey(targetParameterType)) {
                    throw new IllegalArgumentException("Found more than one method match for type "
                            + "[Message<" + targetParameterType + ">]");
                }
                candidateMessageMethods.put(targetParameterType, handlerMethod1);
            } else {
                if (candidateMethods.containsKey(targetParameterType)) {
                    String exceptionMessage = "Found more than one method match for ";
                    if (Void.class.equals(targetParameterType)) {
                        exceptionMessage += "empty parameter for 'payload'";
                    } else {
                        exceptionMessage += "type [" + targetParameterType + "]";
                    }
                    throw new IllegalArgumentException(exceptionMessage);
                }
                candidateMethods.put(targetParameterType, handlerMethod1);
            }
        } else {
            if (handlerMethod1.isMessageMethod()) {
                if (fallbackMessageMethods.containsKey(targetParameterType)) {
                    // we need to check for duplicate type matches,
                    // but only if we end up falling back
                    // and we'll only keep track of the first one
                    ambiguousFallbackMessageGenericType.compareAndSet(null, targetParameterType);
                }
                fallbackMessageMethods.put(targetParameterType, handlerMethod1);
            } else {
                if (fallbackMethods.containsKey(targetParameterType)) {
                    // we need to check for duplicate type matches,
                    // but only if we end up falling back
                    // and we'll only keep track of the first one
                    ambiguousFallbackType.compareAndSet(null, targetParameterType);
                }
                fallbackMethods.put(targetParameterType, handlerMethod1);
            }
        }
    }, methodFilter);

    if (candidateMethods.isEmpty() && candidateMessageMethods.isEmpty() && fallbackMethods.isEmpty()
            && fallbackMessageMethods.isEmpty()) {
        findSingleSpecifMethodOnInterfacesIfProxy(targetObject, methodName, candidateMessageMethods,
                candidateMethods);
    }

    if (!candidateMethods.isEmpty() || !candidateMessageMethods.isEmpty()) {
        handlerMethods.put(CANDIDATE_METHODS, candidateMethods);
        handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods);
        return handlerMethods;
    }
    if ((ambiguousFallbackType.get() != null || ambiguousFallbackMessageGenericType.get() != null)
            && ServiceActivator.class.equals(annotationType)) {
        /*
         * When there are ambiguous fallback methods,
         * a Service Activator can finally fallback to RequestReplyExchanger.exchange(m).
         * Ambiguous means > 1 method that takes the same payload type, or > 1 method
         * that takes a Message with the same generic type.
         */
        List<Method> frameworkMethods = new ArrayList<>();
        Class<?>[] allInterfaces = org.springframework.util.ClassUtils.getAllInterfacesForClass(targetClass);
        for (Class<?> iface : allInterfaces) {
            try {
                if ("org.springframework.integration.gateway.RequestReplyExchanger".equals(iface.getName())) {
                    frameworkMethods.add(targetClass.getMethod("exchange", Message.class));
                    if (logger.isDebugEnabled()) {
                        logger.debug(targetObject.getClass()
                                + ": Ambiguous fallback methods; using RequestReplyExchanger.exchange()");
                    }
                }
            } catch (Exception e) {
                // should never happen (but would fall through to errors below)
            }
        }
        if (frameworkMethods.size() == 1) {
            Method method = org.springframework.util.ClassUtils.getMostSpecificMethod(frameworkMethods.get(0),
                    targetObject.getClass());
            InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory
                    .createInvocableHandlerMethod(targetObject, method);
            HandlerMethod handlerMethod = new HandlerMethod(invocableHandlerMethod, this.canProcessMessageList);
            checkSpelInvokerRequired(targetClass, method, handlerMethod);
            handlerMethods.put(CANDIDATE_METHODS, Collections.singletonMap(Object.class, handlerMethod));
            handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods);
            return handlerMethods;
        }
    }

    Assert.state(!fallbackMethods.isEmpty() || !fallbackMessageMethods.isEmpty(), "Target object of type ["
            + this.targetObject.getClass() + "] has no eligible methods for handling Messages.");

    Assert.isNull(ambiguousFallbackType.get(), "Found ambiguous parameter type [" + ambiguousFallbackType
            + "] for method match: " + fallbackMethods.values());
    Assert.isNull(ambiguousFallbackMessageGenericType.get(), "Found ambiguous parameter type ["
            + ambiguousFallbackMessageGenericType + "] for method match: " + fallbackMethods.values());

    handlerMethods.put(CANDIDATE_METHODS, fallbackMethods);
    handlerMethods.put(CANDIDATE_MESSAGE_METHODS, fallbackMessageMethods);
    return handlerMethods;
}

From source file:org.springframework.integration.handler.support.MessagingMethodInvokerHelper.java

private void checkSpelInvokerRequired(final Class<?> targetClass, Method methodArg,
        HandlerMethod handlerMethod) {//  w  w w  .  j  a v  a 2  s. c o m
    Method method = AopUtils.getMostSpecificMethod(methodArg, targetClass);
    UseSpelInvoker useSpel = AnnotationUtils.findAnnotation(method, UseSpelInvoker.class);
    if (useSpel == null) {
        useSpel = AnnotationUtils.findAnnotation(targetClass, UseSpelInvoker.class);
    }
    if (useSpel != null) {
        handlerMethod.spelOnly = true;
        handlerMethod.useSpelInvoker = useSpel;
    }
}

From source file:org.springframework.integration.util.MessagingMethodInvokerHelper.java

private Map<Class<?>, HandlerMethod> findHandlerMethodsForTarget(final Object targetObject,
        final Class<? extends Annotation> annotationType, final String methodName,
        final boolean requiresReply) {

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>();
    final Map<Class<?>, HandlerMethod> fallbackMethods = new HashMap<Class<?>, HandlerMethod>();
    final AtomicReference<Class<?>> ambiguousFallbackType = new AtomicReference<Class<?>>();
    final Class<?> targetClass = this.getTargetClass(targetObject);
    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            boolean matchesAnnotation = false;
            if (method.isBridge()) {
                return;
            }/* ww w.  j  av  a  2  s . c o  m*/
            if (isMethodDefinedOnObjectClass(method)) {
                return;
            }
            if (method.getDeclaringClass().equals(Proxy.class)) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (requiresReply && void.class.equals(method.getReturnType())) {
                return;
            }
            if (methodName != null && !methodName.equals(method.getName())) {
                return;
            }
            if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) {
                matchesAnnotation = true;
            }
            HandlerMethod handlerMethod = null;
            try {
                handlerMethod = new HandlerMethod(method, canProcessMessageList);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Method [" + method + "] is not eligible for Message handling.", e);
                }
                return;
            }
            Class<?> targetParameterType = handlerMethod.getTargetParameterType().getObjectType();
            if (matchesAnnotation || annotationType == null) {
                Assert.isTrue(!candidateMethods.containsKey(targetParameterType),
                        "Found more than one method match for type [" + targetParameterType + "]");
                candidateMethods.put(targetParameterType, handlerMethod);
            } else {
                if (fallbackMethods.containsKey(targetParameterType)) {
                    // we need to check for duplicate type matches,
                    // but only if we end up falling back
                    // and we'll only keep track of the first one
                    ambiguousFallbackType.compareAndSet(null, targetParameterType);
                }
                fallbackMethods.put(targetParameterType, handlerMethod);
            }
        }
    }, methodFilter);
    if (!candidateMethods.isEmpty()) {
        return candidateMethods;
    }
    if ((fallbackMethods.isEmpty() || ambiguousFallbackType.get() != null)
            && ServiceActivator.class.equals(annotationType)) {
        // a Service Activator can fallback to either MessageHandler.handleMessage(m) or RequestReplyExchanger.exchange(m)
        List<Method> frameworkMethods = new ArrayList<Method>();
        Class<?>[] allInterfaces = org.springframework.util.ClassUtils.getAllInterfacesForClass(targetClass);
        for (Class<?> iface : allInterfaces) {
            try {
                if ("org.springframework.integration.gateway.RequestReplyExchanger".equals(iface.getName())) {
                    frameworkMethods.add(targetClass.getMethod("exchange", Message.class));
                } else if ("org.springframework.integration.core.MessageHandler".equals(iface.getName())
                        && !requiresReply) {
                    frameworkMethods.add(targetClass.getMethod("handleMessage", Message.class));
                }
            } catch (Exception e) {
                // should never happen (but would fall through to errors below)
            }
        }
        if (frameworkMethods.size() == 1) {
            HandlerMethod handlerMethod = new HandlerMethod(frameworkMethods.get(0), canProcessMessageList);
            return Collections.<Class<?>, HandlerMethod>singletonMap(Object.class, handlerMethod);
        }
    }
    Assert.notEmpty(fallbackMethods, "Target object of type [" + this.targetObject.getClass()
            + "] has no eligible methods for handling Messages.");
    Assert.isNull(ambiguousFallbackType.get(), "Found ambiguous parameter type [" + ambiguousFallbackType
            + "] for method match: " + fallbackMethods.values());
    return fallbackMethods;
}

From source file:org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        Collection<KafkaListener> classLevelListeners = findListenerAnnotations(targetClass);
        final boolean hasClassLevelListeners = classLevelListeners.size() > 0;
        final List<Method> multiMethods = new ArrayList<Method>();
        Map<Method, Set<KafkaListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
                new MethodIntrospector.MetadataLookup<Set<KafkaListener>>() {

                    @Override//from   w  w  w  .ja  va  2s  .  c  om
                    public Set<KafkaListener> inspect(Method method) {
                        Set<KafkaListener> listenerMethods = findListenerAnnotations(method);
                        return (!listenerMethods.isEmpty() ? listenerMethods : null);
                    }

                });
        if (hasClassLevelListeners) {
            Set<Method> methodsWithHandler = MethodIntrospector.selectMethods(targetClass,
                    new ReflectionUtils.MethodFilter() {

                        @Override
                        public boolean matches(Method method) {
                            return AnnotationUtils.findAnnotation(method, KafkaHandler.class) != null;
                        }

                    });
            multiMethods.addAll(methodsWithHandler);
        }
        if (annotatedMethods.isEmpty()) {
            this.nonAnnotatedClasses.add(bean.getClass());
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("No @KafkaListener annotations found on bean type: " + bean.getClass());
            }
        } else {
            // Non-empty set of methods
            for (Map.Entry<Method, Set<KafkaListener>> entry : annotatedMethods.entrySet()) {
                Method method = entry.getKey();
                for (KafkaListener listener : entry.getValue()) {
                    processKafkaListener(listener, method, bean, beanName);
                }
            }
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(annotatedMethods.size() + " @KafkaListener methods processed on bean '"
                        + beanName + "': " + annotatedMethods);
            }
        }
        if (hasClassLevelListeners) {
            processMultiMethodListeners(classLevelListeners, multiMethods, bean, beanName);
        }
    }
    return bean;
}

From source file:org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.java

private Collection<KafkaListener> findListenerAnnotations(Class<?> clazz) {
    Set<KafkaListener> listeners = new HashSet<KafkaListener>();
    KafkaListener ann = AnnotationUtils.findAnnotation(clazz, KafkaListener.class);
    if (ann != null) {
        listeners.add(ann);//  w  ww. j  a  va2 s . c o m
    }
    KafkaListeners anns = AnnotationUtils.findAnnotation(clazz, KafkaListeners.class);
    if (anns != null) {
        listeners.addAll(Arrays.asList(anns.value()));
    }
    return listeners;
}

From source file:org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.java

private Set<KafkaListener> findListenerAnnotations(Method method) {
    Set<KafkaListener> listeners = new HashSet<KafkaListener>();
    KafkaListener ann = AnnotationUtils.findAnnotation(method, KafkaListener.class);
    if (ann != null) {
        listeners.add(ann);//ww w .j a  v  a  2s.c  o  m
    }
    KafkaListeners anns = AnnotationUtils.findAnnotation(method, KafkaListeners.class);
    if (anns != null) {
        listeners.addAll(Arrays.asList(anns.value()));
    }
    return listeners;
}

From source file:org.springframework.messaging.handler.method.HandlerMethod.java

/**
 * Returns a single annotation on the underlying method traversing its super methods if no
 * annotation can be found on the given method itself.
 * @param annotationType the type of annotation to introspect the method for.
 * @return the annotation, or {@code null} if none found
 *//* w  w  w .ja v a 2s.  co m*/
public <A extends Annotation> A getMethodAnnotation(Class<A> annotationType) {
    return AnnotationUtils.findAnnotation(this.method, annotationType);
}

From source file:org.springframework.messaging.simp.handler.AnnotationMethodMessageHandler.java

protected boolean isHandler(Class<?> beanType) {
    return (AnnotationUtils.findAnnotation(beanType, Controller.class) != null);
}

From source file:org.springframework.messaging.simp.handler.AnnotationMethodMessageHandler.java

private <A extends Annotation> void initHandlerMethods(Object handler, Class<?> handlerType,
        final Class<A> annotationType, MappingInfoCreator<A> mappingInfoCreator,
        Map<MappingInfo, HandlerMethod> handlerMethods) {

    Set<Method> messageMethods = HandlerMethodSelector.selectMethods(handlerType, new MethodFilter() {
        @Override//from w w  w .j  a  v  a2s  .c  o m
        public boolean matches(Method method) {
            return AnnotationUtils.findAnnotation(method, annotationType) != null;
        }
    });

    for (Method method : messageMethods) {
        A annotation = AnnotationUtils.findAnnotation(method, annotationType);
        HandlerMethod hm = createHandlerMethod(handler, method);
        handlerMethods.put(mappingInfoCreator.create(annotation), hm);
    }
}