Example usage for org.springframework.core MethodIntrospector selectMethods

List of usage examples for org.springframework.core MethodIntrospector selectMethods

Introduction

In this page you can find the example usage for org.springframework.core MethodIntrospector selectMethods.

Prototype

public static Set<Method> selectMethods(Class<?> targetType, final ReflectionUtils.MethodFilter methodFilter) 

Source Link

Document

Select methods on the given target type based on a filter.

Usage

From source file:ch.ralscha.extdirectspring.controller.MethodRegistrar.java

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

    ApplicationContext context = (ApplicationContext) event.getSource();

    String[] beanNames = context.getBeanNamesForType(Object.class);

    for (String beanName : beanNames) {

        Class<?> handlerType = context.getType(beanName);
        final Class<?> userType = ClassUtils.getUserClass(handlerType);

        Set<Method> methods = MethodIntrospector.selectMethods(userType, new MethodFilter() {
            @Override/*from  w w w .  j  a  va2  s  . c  o m*/
            public boolean matches(Method method) {
                return AnnotationUtils.findAnnotation(method, ExtDirectMethod.class) != null;
            }
        });

        for (Method method : methods) {
            ExtDirectMethod directMethodAnnotation = AnnotationUtils.findAnnotation(method,
                    ExtDirectMethod.class);
            final String beanAndMethodName = beanName + "." + method.getName();
            if (directMethodAnnotation.value().isValid(beanAndMethodName, userType, method)) {
                this.methodInfoCache.put(beanName, handlerType, method, event.getApplicationContext());

                // /CLOVER:OFF
                if (log.isDebugEnabled()) {
                    String info = "Register " + beanAndMethodName + "(" + directMethodAnnotation.value();
                    if (StringUtils.hasText(directMethodAnnotation.group())) {
                        info += ", " + directMethodAnnotation.group();
                    }
                    info += ")";
                    log.debug(info);
                }
                // /CLOVER:ON
            }
        }

    }
}

From source file:dstrelec.nats.annotation.NatsListenerAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    if (beanName.equals("myListener")) {
        System.out.println(beanName);
    }//  w ww . jav a  2s.c  o  m
    if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        Collection<NatsListener> classLevelListeners = findListenerAnnotations(targetClass);
        final boolean hasClassLevelListeners = classLevelListeners.size() > 0;
        final List<Method> multiMethods = new ArrayList<>();
        Map<Method, Set<NatsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
                (MethodIntrospector.MetadataLookup<Set<NatsListener>>) method -> {
                    Set<NatsListener> listenerMethods = findListenerAnnotations(method);
                    return (!listenerMethods.isEmpty() ? listenerMethods : null);
                });
        if (hasClassLevelListeners) {
            Set<Method> methodsWithHandler = MethodIntrospector.selectMethods(targetClass,
                    (ReflectionUtils.MethodFilter) method -> AnnotationUtils.findAnnotation(method,
                            NatsHandler.class) != null);
            multiMethods.addAll(methodsWithHandler);
        }
        if (annotatedMethods.isEmpty()) {
            this.nonAnnotatedClasses.add(bean.getClass());
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("No @NatsListener annotations found on bean type: " + bean.getClass());
            }
        } else {
            // Non-empty set of methods
            for (Map.Entry<Method, Set<NatsListener>> entry : annotatedMethods.entrySet()) {
                Method method = entry.getKey();
                for (NatsListener listener : entry.getValue()) {
                    processNatsListener(listener, method, bean, beanName);
                }
            }
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(annotatedMethods.size() + " @NatsListener methods processed on bean '"
                        + beanName + "': " + annotatedMethods);
            }
        }
        if (hasClassLevelListeners) {
            processMultiMethodListeners(classLevelListeners, multiMethods, bean, beanName);
        }
    }
    return bean;
}

From source file:org.springframework.context.event.EventListenerMethodProcessor.java

protected void processBean(final List<EventListenerFactory> factories, final String beanName,
        final Class<?> targetType) {

    if (!this.nonAnnotatedClasses.contains(targetType)) {
        Map<Method, EventListener> annotatedMethods = null;
        try {/*from w  w w  .  j  a  v  a2  s .  com*/
            annotatedMethods = MethodIntrospector.selectMethods(targetType,
                    (MethodIntrospector.MetadataLookup<EventListener>) method -> AnnotatedElementUtils
                            .findMergedAnnotation(method, EventListener.class));
        } catch (Throwable ex) {
            // An unresolvable type in a method signature, probably from a lazy bean - let's ignore it.
            if (logger.isDebugEnabled()) {
                logger.debug("Could not resolve methods for bean with name '" + beanName + "'", ex);
            }
        }
        if (CollectionUtils.isEmpty(annotatedMethods)) {
            this.nonAnnotatedClasses.add(targetType);
            if (logger.isTraceEnabled()) {
                logger.trace("No @EventListener annotations found on bean class: " + targetType.getName());
            }
        } else {
            // Non-empty set of methods
            ConfigurableApplicationContext context = getApplicationContext();
            for (Method method : annotatedMethods.keySet()) {
                for (EventListenerFactory factory : factories) {
                    if (factory.supportsMethod(method)) {
                        Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
                        ApplicationListener<?> applicationListener = factory.createApplicationListener(beanName,
                                targetType, methodToUse);
                        if (applicationListener instanceof ApplicationListenerMethodAdapter) {
                            ((ApplicationListenerMethodAdapter) applicationListener).init(context,
                                    this.evaluator);
                        }
                        context.addApplicationListener(applicationListener);
                        break;
                    }
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" + beanName
                        + "': " + annotatedMethods);
            }
        }
    }
}

From source file:org.springframework.jms.annotation.JmsListenerAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
    if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
        Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
        Map<Method, Set<JmsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
                (MethodIntrospector.MetadataLookup<Set<JmsListener>>) method -> {
                    Set<JmsListener> listenerMethods = AnnotatedElementUtils
                            .getMergedRepeatableAnnotations(method, JmsListener.class, JmsListeners.class);
                    return (!listenerMethods.isEmpty() ? listenerMethods : null);
                });//from w  w w  .ja  v a 2 s.  c o m
        if (annotatedMethods.isEmpty()) {
            this.nonAnnotatedClasses.add(bean.getClass());
            if (logger.isTraceEnabled()) {
                logger.trace("No @JmsListener annotations found on bean type: " + bean.getClass());
            }
        } else {
            // Non-empty set of methods
            annotatedMethods.forEach((method, listeners) -> listeners
                    .forEach(listener -> processJmsListener(listener, method, bean)));
            if (logger.isDebugEnabled()) {
                logger.debug(annotatedMethods.size() + " @JmsListener methods processed on bean '" + beanName
                        + "': " + annotatedMethods);
            }
        }
    }
    return bean;
}

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  ww  . j a  v  a  2 s . co  m*/
                    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.messaging.handler.invocation.AbstractMethodMessageHandler.java

/**
 * Detect if the given handler has any methods that can handle messages and if
 * so register it with the extracted mapping information.
 * @param handler the handler to check, either an instance of a Spring bean name
 *//*from w w  w .j a  v  a2  s.co m*/
protected final void detectHandlerMethods(final Object handler) {
    Class<?> handlerType;
    if (handler instanceof String) {
        ApplicationContext context = getApplicationContext();
        Assert.state(context != null, "ApplicationContext is required for resolving handler bean names");
        handlerType = context.getType((String) handler);
    } else {
        handlerType = handler.getClass();
    }

    if (handlerType != null) {
        final Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
        if (logger.isDebugEnabled()) {
            logger.debug(methods.size() + " message handler methods found on " + userType + ": " + methods);
        }
        methods.forEach((key, value) -> registerHandlerMethod(handler, key, value));
    }
}

From source file:org.springframework.messaging.handler.invocation.reactive.AbstractMethodMessageHandler.java

/**
 * Detect if the given handler has any methods that can handle messages and if
 * so register it with the extracted mapping information.
 * <p><strong>Note:</strong> This method is protected and can be invoked by
 * sub-classes, but this should be done on startup only as documented in
 * {@link #registerHandlerMethod}.//w  ww . j  a va2  s .com
 * @param handler the handler to check, either an instance of a Spring bean name
 */
protected final void detectHandlerMethods(Object handler) {
    Class<?> handlerType;
    if (handler instanceof String) {
        ApplicationContext context = getApplicationContext();
        Assert.state(context != null, "ApplicationContext is required for resolving handler bean names");
        handlerType = context.getType((String) handler);
    } else {
        handlerType = handler.getClass();
    }
    if (handlerType != null) {
        final Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
        if (logger.isDebugEnabled()) {
            logger.debug(formatMappings(userType, methods));
        }
        methods.forEach((key, value) -> registerHandlerMethod(handler, key, value));
    }
}

From source file:org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
    if (!this.nonAnnotatedClasses.contains(targetClass)) {
        Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
                (MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {
                    Set<Scheduled> scheduledMethods = AnnotatedElementUtils
                            .getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class);
                    return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
                });/*from  w ww. j  av  a  2s. c  om*/
        if (annotatedMethods.isEmpty()) {
            this.nonAnnotatedClasses.add(targetClass);
            if (logger.isTraceEnabled()) {
                logger.trace("No @Scheduled annotations found on bean class: " + bean.getClass());
            }
        } else {
            // Non-empty set of methods
            annotatedMethods.forEach((method, scheduledMethods) -> scheduledMethods
                    .forEach(scheduled -> processScheduled(scheduled, method, bean)));
            if (logger.isDebugEnabled()) {
                logger.debug(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName
                        + "': " + annotatedMethods);
            }
        }
    }
    return bean;
}

From source file:org.springframework.web.method.annotation.ModelFactoryOrderingTests.java

private void runTest(Object controller) throws Exception {
    HandlerMethodArgumentResolverComposite resolvers = new HandlerMethodArgumentResolverComposite();
    resolvers.addResolver(new ModelAttributeMethodProcessor(false));
    resolvers.addResolver(new ModelMethodProcessor());
    WebDataBinderFactory dataBinderFactory = new DefaultDataBinderFactory(null);

    Class<?> type = controller.getClass();
    Set<Method> methods = MethodIntrospector.selectMethods(type, METHOD_FILTER);
    List<InvocableHandlerMethod> modelMethods = new ArrayList<>();
    for (Method method : methods) {
        InvocableHandlerMethod modelMethod = new InvocableHandlerMethod(controller, method);
        modelMethod.setHandlerMethodArgumentResolvers(resolvers);
        modelMethod.setDataBinderFactory(dataBinderFactory);
        modelMethods.add(modelMethod);/*from   ww  w .  ja v a  2 s  .  com*/
    }
    Collections.shuffle(modelMethods);

    SessionAttributesHandler sessionHandler = new SessionAttributesHandler(type, this.sessionAttributeStore);
    ModelFactory factory = new ModelFactory(modelMethods, dataBinderFactory, sessionHandler);
    factory.initModel(this.webRequest, this.mavContainer, new HandlerMethod(controller, "handle"));
    if (logger.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (String name : getInvokedMethods()) {
            sb.append(" >> ").append(name);
        }
        logger.debug(sb);
    }
}

From source file:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.java

/**
 * Look for handler methods in a handler.
 * @param handler the bean name of a handler or a handler instance
 *///from   w  w w. j  a  v  a2s .  c o m
protected void detectHandlerMethods(final Object handler) {
    Class<?> handlerType = (handler instanceof String ? obtainApplicationContext().getType((String) handler)
            : handler.getClass());

    if (handlerType != null) {
        final Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<T>) method -> {
                    try {
                        return getMappingForMethod(method, userType);
                    } catch (Throwable ex) {
                        throw new IllegalStateException(
                                "Invalid mapping on handler class [" + userType.getName() + "]: " + method, ex);
                    }
                });
        if (logger.isTraceEnabled()) {
            logger.trace("Mapped " + methods.size() + " handler method(s) for " + userType + ": " + methods);
        }
        methods.forEach((method, mapping) -> {
            Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
            registerHandlerMethod(handler, invocableMethod, mapping);
        });
    }
}