Example usage for org.springframework.core.annotation AnnotatedElementUtils findMergedAnnotation

List of usage examples for org.springframework.core.annotation AnnotatedElementUtils findMergedAnnotation

Introduction

In this page you can find the example usage for org.springframework.core.annotation AnnotatedElementUtils findMergedAnnotation.

Prototype

@Nullable
public static <A extends Annotation> A findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) 

Source Link

Document

Find the first annotation of the specified annotationType within the annotation hierarchy above the supplied element , merge that annotation's attributes with matching attributes from annotations in lower levels of the annotation hierarchy, and synthesize the result back into an annotation of the specified annotationType .

Usage

From source file:com.github.ljtfreitas.restify.http.spring.contract.metadata.reflection.SpringWebJavaMethodMetadata.java

public SpringWebJavaMethodMetadata(Method javaMethod) {
    this.javaMethod = javaMethod;

    RequestMapping mapping = Optional
            .ofNullable(AnnotatedElementUtils.findMergedAnnotation(javaMethod, RequestMapping.class))
            .orElseThrow(() -> new IllegalArgumentException(
                    "Method [" + javaMethod + "] does not have a @RequestMapping annotation."));

    isTrue(mapping.value().length <= 1, "Only single path is allowed.");
    isTrue(mapping.method().length == 1,
            "You must set the HTTP method (only one!) of your Java method [" + javaMethod + "].");

    this.mapping = new SpringWebRequestMappingMetadata(mapping);
}

From source file:org.springframework.boot.test.context.SpringBootTestContextBootstrapper.java

@Override
protected MergedContextConfiguration processMergedContextConfiguration(
        MergedContextConfiguration mergedConfig) {
    Class<?>[] classes = getOrFindConfigurationClasses(mergedConfig);
    List<String> propertySourceProperties = getAndProcessPropertySourceProperties(mergedConfig);
    mergedConfig = createModifiedConfig(mergedConfig, classes,
            propertySourceProperties.toArray(new String[propertySourceProperties.size()]));
    WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass());
    if (webEnvironment != null) {
        if (webEnvironment.isEmbedded()
                || (webEnvironment == WebEnvironment.MOCK && hasWebEnvironmentClasses())) {
            WebAppConfiguration webAppConfiguration = AnnotatedElementUtils
                    .findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class);
            String resourceBasePath = (webAppConfiguration == null ? "src/main/webapp"
                    : webAppConfiguration.value());
            mergedConfig = new WebMergedContextConfiguration(mergedConfig, resourceBasePath);
        }//w  ww  .  j a v  a 2  s .co m
    }
    return mergedConfig;
}

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

public ApplicationListenerMethodAdapter(String beanName, Class<?> targetClass, Method method) {
    this.beanName = beanName;
    this.method = method;
    this.targetClass = targetClass;
    this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);

    Method targetMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    EventListener ann = AnnotatedElementUtils.findMergedAnnotation(targetMethod, EventListener.class);

    this.declaredEventTypes = resolveDeclaredEventTypes(method, ann);
    this.condition = (ann != null ? ann.condition() : null);
    this.order = resolveOrder(method);

    this.methodKey = new AnnotatedElementKey(method, targetClass);
}

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

private int resolveOrder(Method method) {
    Order ann = AnnotatedElementUtils.findMergedAnnotation(method, Order.class);
    return (ann != null ? ann.value() : 0);
}

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  av  a 2s . c  om
            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.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport.java

/**
 * Resolves the {@link Annotation} with the given {@link Class type} from the {@link AnnotatedElement}.
 *
 * @param <A> {@link Class Subclass type} of the resolved {@link Annotation}.
 * @param annotatedElement {@link AnnotatedElement} from which to resolve the {@link Annotation}.
 * @param annotationType {@link Class type} of the {@link Annotation} to resolve from the {@link AnnotatedElement}.
 * @return the resolved {@link Annotation}.
 * @see java.lang.annotation.Annotation//from   www.  j  a  va 2 s  .  c  o m
 * @see java.lang.reflect.AnnotatedElement
 * @see java.lang.Class
 */
protected <A extends Annotation> A resolveAnnotation(AnnotatedElement annotatedElement,
        Class<A> annotationType) {

    return (annotatedElement instanceof Class
            ? AnnotatedElementUtils.findMergedAnnotation(annotatedElement, annotationType)
            : AnnotationUtils.findAnnotation(annotatedElement, annotationType));
}

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

/**
 * Return a single annotation on the underlying method traversing its super methods
 * if no annotation can be found on the given method itself.
 * <p>Also supports <em>merged</em> composed annotations with attribute
 * overrides as of Spring Framework 4.3.
 * @param annotationType the type of annotation to introspect the method for
 * @return the annotation, or {@code null} if none found
 * @see AnnotatedElementUtils#findMergedAnnotation
 *//*from   w  w w. ja v  a2s .c  o  m*/
@Nullable
public <A extends Annotation> A getMethodAnnotation(Class<A> annotationType) {
    return AnnotatedElementUtils.findMergedAnnotation(this.method, annotationType);
}

From source file:org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.java

@Override
@Nullable// w  w w.  j av  a2  s  .  c  om
protected SimpMessageMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    MessageMapping messageAnn = AnnotatedElementUtils.findMergedAnnotation(method, MessageMapping.class);
    if (messageAnn != null) {
        MessageMapping typeAnn = AnnotatedElementUtils.findMergedAnnotation(handlerType, MessageMapping.class);
        // Only actually register it if there are destinations specified;
        // otherwise @MessageMapping is just being used as a (meta-annotation) marker.
        if (messageAnn.value().length > 0 || (typeAnn != null && typeAnn.value().length > 0)) {
            SimpMessageMappingInfo result = createMessageMappingCondition(messageAnn.value());
            if (typeAnn != null) {
                result = createMessageMappingCondition(typeAnn.value()).combine(result);
            }
            return result;
        }
    }

    SubscribeMapping subscribeAnn = AnnotatedElementUtils.findMergedAnnotation(method, SubscribeMapping.class);
    if (subscribeAnn != null) {
        MessageMapping typeAnn = AnnotatedElementUtils.findMergedAnnotation(handlerType, MessageMapping.class);
        // Only actually register it if there are destinations specified;
        // otherwise @SubscribeMapping is just being used as a (meta-annotation) marker.
        if (subscribeAnn.value().length > 0 || (typeAnn != null && typeAnn.value().length > 0)) {
            SimpMessageMappingInfo result = createSubscribeMappingCondition(subscribeAnn.value());
            if (typeAnn != null) {
                result = createMessageMappingCondition(typeAnn.value()).combine(result);
            }
            return result;
        }
    }

    return null;
}

From source file:org.springframework.test.annotation.ProfileValueUtils.java

/**
 * Retrieves the {@link ProfileValueSource} type for the specified
 * {@link Class test class} as configured via the
 * {@link ProfileValueSourceConfiguration
 * &#064;ProfileValueSourceConfiguration} annotation and instantiates a new
 * instance of that type.//from w  w w  .j a  va 2s  .  c om
 * <p>If {@link ProfileValueSourceConfiguration
 * &#064;ProfileValueSourceConfiguration} is not present on the specified
 * class or if a custom {@link ProfileValueSource} is not declared, the
 * default {@link SystemProfileValueSource} will be returned instead.
 * @param testClass The test class for which the ProfileValueSource should
 * be retrieved
 * @return the configured (or default) ProfileValueSource for the specified
 * class
 * @see SystemProfileValueSource
 */
@SuppressWarnings("unchecked")
public static ProfileValueSource retrieveProfileValueSource(Class<?> testClass) {
    Assert.notNull(testClass, "testClass must not be null");

    Class<ProfileValueSourceConfiguration> annotationType = ProfileValueSourceConfiguration.class;
    ProfileValueSourceConfiguration config = AnnotatedElementUtils.findMergedAnnotation(testClass,
            annotationType);
    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved @ProfileValueSourceConfiguration [" + config + "] for test class ["
                + testClass.getName() + "]");
    }

    Class<? extends ProfileValueSource> profileValueSourceType;
    if (config != null) {
        profileValueSourceType = config.value();
    } else {
        profileValueSourceType = (Class<? extends ProfileValueSource>) AnnotationUtils
                .getDefaultValue(annotationType);
        Assert.state(profileValueSourceType != null, "No default ProfileValueSource class");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved ProfileValueSource type [" + profileValueSourceType + "] for class ["
                + testClass.getName() + "]");
    }

    ProfileValueSource profileValueSource;
    if (SystemProfileValueSource.class == profileValueSourceType) {
        profileValueSource = SystemProfileValueSource.getInstance();
    } else {
        try {
            profileValueSource = ReflectionUtils.accessibleConstructor(profileValueSourceType).newInstance();
        } catch (Exception ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Could not instantiate a ProfileValueSource of type [" + profileValueSourceType
                        + "] for class [" + testClass.getName() + "]: using default.", ex);
            }
            profileValueSource = SystemProfileValueSource.getInstance();
        }
    }

    return profileValueSource;
}

From source file:org.springframework.test.annotation.ProfileValueUtils.java

/**
 * Determine if the supplied {@code testClass} is <em>enabled</em> in
 * the current environment, as specified by the {@link IfProfileValue
 * &#064;IfProfileValue} annotation at the class level.
 * <p>Defaults to {@code true} if no {@link IfProfileValue
 * &#064;IfProfileValue} annotation is declared.
 * @param testClass the test class/*from   w ww  . j  a  v a2s .  com*/
 * @return {@code true} if the test is <em>enabled</em> in the current
 * environment
 */
public static boolean isTestEnabledInThisEnvironment(Class<?> testClass) {
    IfProfileValue ifProfileValue = AnnotatedElementUtils.findMergedAnnotation(testClass, IfProfileValue.class);
    return isTestEnabledInThisEnvironment(retrieveProfileValueSource(testClass), ifProfileValue);
}