Java Code Examples for org.springframework.core.annotation.AnnotatedElementUtils#findMergedAnnotation()

The following examples show how to use org.springframework.core.annotation.AnnotatedElementUtils#findMergedAnnotation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassUtil.java    From mica with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取Annotation
 *
 * @param method         Method
 * @param annotationType 注解类
 * @param <A>            泛型标记
 * @return {Annotation}
 */
@Nullable
public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
	Class<?> targetClass = method.getDeclaringClass();
	// The method may be on an interface, but we need attributes from the target class.
	// If the target class is null, the method will be unchanged.
	Method specificMethod = ClassUtil.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	// 先找方法,再找方法上的类
	A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
	if (null != annotation) {
		return annotation;
	}
	// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
	return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
}
 
Example 2
Source File: SendToMethodReturnValueHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
private DestinationHelper getDestinationHelper(MessageHeaders headers, MethodParameter returnType) {
	SendToUser m1 = AnnotatedElementUtils.findMergedAnnotation(returnType.getExecutable(), SendToUser.class);
	SendTo m2 = AnnotatedElementUtils.findMergedAnnotation(returnType.getExecutable(), SendTo.class);
	if ((m1 != null && !ObjectUtils.isEmpty(m1.value())) || (m2 != null && !ObjectUtils.isEmpty(m2.value()))) {
		return new DestinationHelper(headers, m1, m2);
	}

	SendToUser c1 = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendToUser.class);
	SendTo c2 = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendTo.class);
	if ((c1 != null && !ObjectUtils.isEmpty(c1.value())) || (c2 != null && !ObjectUtils.isEmpty(c2.value()))) {
		return new DestinationHelper(headers, c1, c2);
	}

	return (m1 != null || m2 != null ?
			new DestinationHelper(headers, m1, m2) : new DestinationHelper(headers, c1, c2));
}
 
Example 3
Source File: WebSocketRouterFactory.java    From netstrap with Apache License 2.0 6 votes vote down vote up
/**
 * 构建路由对象
 */
private void buildMethod(Object invoker, Method method, String groupUri, String slash) {
    WebSocketAction router = new WebSocketAction();
    router.setInvoker(invoker);
    method.setAccessible(true);

    WebSocketMapping mapping = AnnotatedElementUtils.findMergedAnnotation(method, WebSocketMapping.class);
    if (Objects.nonNull(mapping)) {
        String mappingUri = mapping.value();
        if (!StringUtils.isEmpty(mappingUri)) {
            mappingUri = (mappingUri.startsWith(slash) ? mappingUri : slash + mappingUri);
            router.setAction(method);
            router.setUri(groupUri + mappingUri);
            put(router.getUri(), router);
            router.setMappings(buildArguments(method));
        }
    }
}
 
Example 4
Source File: ProfileValueChecker.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Determine if the test specified by arguments to the
 * {@linkplain #ProfileValueChecker constructor} is <em>enabled</em> in
 * the current environment, as configured via the {@link IfProfileValue
 * &#064;IfProfileValue} annotation.
 * <p>If the test is not annotated with {@code @IfProfileValue} it is
 * considered enabled.
 * <p>If a test is not enabled, this method will abort further evaluation
 * of the execution chain with a failed assumption; otherwise, this method
 * will simply evaluate the next {@link Statement} in the execution chain.
 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Class)
 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Method, Class)
 * @throws AssumptionViolatedException if the test is disabled
 * @throws Throwable if evaluation of the next statement fails
 */
@Override
public void evaluate() throws Throwable {
	if (this.testMethod == null) {
		if (!ProfileValueUtils.isTestEnabledInThisEnvironment(this.testClass)) {
			Annotation ann = AnnotatedElementUtils.findMergedAnnotation(this.testClass, IfProfileValue.class);
			throw new AssumptionViolatedException(String.format(
					"Profile configured via [%s] is not enabled in this environment for test class [%s].",
					ann, this.testClass.getName()));
		}
	}
	else {
		if (!ProfileValueUtils.isTestEnabledInThisEnvironment(this.testMethod, this.testClass)) {
			throw new AssumptionViolatedException(String.format(
					"Profile configured via @IfProfileValue is not enabled in this environment for test method [%s].",
					this.testMethod));
		}
	}

	this.next.evaluate();
}
 
Example 5
Source File: CrossOriginTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 6
Source File: TestAnnotationUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Get the {@code timeout} configured via the {@link Timed @Timed}
 * annotation on the supplied {@code method}.
 * <p>Negative configured values will be converted to {@code 0}.
 * @return the configured timeout, or {@code 0} if the method is not
 * annotated with {@code @Timed}
 */
public static long getTimeout(Method method) {
	Timed timed = AnnotatedElementUtils.findMergedAnnotation(method, Timed.class);
	if (timed == null) {
		return 0;
	}
	return Math.max(0, timed.millis());
}
 
Example 7
Source File: HandlerMethod.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void evaluateResponseStatus() {
	ResponseStatus annotation = getMethodAnnotation(ResponseStatus.class);
	if (annotation == null) {
		annotation = AnnotatedElementUtils.findMergedAnnotation(getBeanType(), ResponseStatus.class);
	}
	if (annotation != null) {
		this.responseStatus = annotation.code();
		this.responseStatusReason = annotation.reason();
	}
}
 
Example 8
Source File: MvcUriComponentsBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static String getClassMapping(Class<?> controllerType) {
	Assert.notNull(controllerType, "'controllerType' must not be null");
	RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(controllerType, RequestMapping.class);
	if (mapping == null) {
		return "/";
	}
	String[] paths = mapping.path();
	if (ObjectUtils.isEmpty(paths) || StringUtils.isEmpty(paths[0])) {
		return "/";
	}
	if (paths.length > 1 && logger.isTraceEnabled()) {
		logger.trace("Using first of multiple paths on " + controllerType.getName());
	}
	return paths[0];
}
 
Example 9
Source File: WebTestContextBootstrapper.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Returns a {@link WebMergedContextConfiguration} if the test class in the
 * supplied {@code MergedContextConfiguration} is annotated with
 * {@link WebAppConfiguration @WebAppConfiguration} and otherwise returns
 * the supplied instance unmodified.
 */
@Override
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
	WebAppConfiguration webAppConfiguration =
			AnnotatedElementUtils.findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class);
	if (webAppConfiguration != null) {
		return new WebMergedContextConfiguration(mergedConfig, webAppConfiguration.value());
	}
	else {
		return mergedConfig;
	}
}
 
Example 10
Source File: MvcAnnotationPredicates.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean test(Method method) {
	RequestMapping annot = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	return annot != null &&
			Arrays.equals(this.path, annot.path()) &&
			Arrays.equals(this.method, annot.method()) &&
			(this.params == null || Arrays.equals(this.params, annot.params()));
}
 
Example 11
Source File: MvcAnnotationPredicates.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean test(Method method) {
	RequestMapping annot = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	return annot != null &&
			Arrays.equals(this.path, annot.path()) &&
			Arrays.equals(this.method, annot.method()) &&
			(this.params == null || Arrays.equals(this.params, annot.params()));
}
 
Example 12
Source File: ApplicationListenerMethodAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return the condition to use.
 * <p>Matches the {@code condition} attribute of the {@link EventListener}
 * annotation or any matching attribute on a composed annotation that
 * is meta-annotated with {@code @EventListener}.
 */
protected String getCondition() {
	if (this.condition == null) {
		EventListener eventListener = AnnotatedElementUtils.findMergedAnnotation(this.method, EventListener.class);
		if (eventListener != null) {
			this.condition = eventListener.condition();
		}
	}
	return this.condition;
}
 
Example 13
Source File: WebFluxResponseStatusExceptionHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
protected HttpStatus determineStatus(Throwable ex) {
	HttpStatus status = super.determineStatus(ex);
	if (status == null) {
		ResponseStatus ann = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
		if (ann != null) {
			status = ann.code();
		}
	}
	return status;
}
 
Example 14
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate response status string.
 *
 * @param method the method
 * @param beanType the bean type
 * @param isGeneric the is generic
 * @return the string
 */
public String evaluateResponseStatus(Method method, Class<?> beanType, boolean isGeneric) {
	String responseStatus = null;
	ResponseStatus annotation = AnnotatedElementUtils.findMergedAnnotation(method, ResponseStatus.class);
	if (annotation == null && beanType != null)
		annotation = AnnotatedElementUtils.findMergedAnnotation(beanType, ResponseStatus.class);
	if (annotation != null)
		responseStatus = String.valueOf(annotation.code().value());
	if (annotation == null && !isGeneric)
		responseStatus = String.valueOf(HttpStatus.OK.value());
	return responseStatus;
}
 
Example 15
Source File: ControllerHelpers.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getRoute(Class<?> controllerClass,String controllerName, boolean isPath) {
    GenRoute routeAnno = AnnotatedElementUtils.findMergedAnnotation(controllerClass, GenRoute.class);
    
    if (routeAnno == null || !routeAnno.value()) {
        return null;
    }
    String route=StringUtil.trimRight(controllerName, CONTROLLER_SUBFIX);
    
    route = StringUtil.uncapfirst(route);
    int size = route.length() + 8;
    StringBuffer sb = new StringBuffer(size);
    String[] subRoutes = route.split(StringUtil.UNDERLINE);
    for (int i = 0; i < subRoutes.length; i++) {
        String subRoute = subRoutes[i];
        if (StringUtil.isNotEmpty(subRoute)) {
            if (i != 0) {
                sb.append(StringUtil.SLASH);
            }
            if (subRoute.startsWith(StringUtil.$)) {
                String repl = isPath ? StringUtil.$ : StringUtil.COLON;
                sb.append(repl);
                subRoute = subRoute.substring(1);
            }
            sb.append(subRoute);
        }
    }

    route = sb.toString();
    return route;
}
 
Example 16
Source File: ApplicationListenerMethodTransactionalAdapterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void assertPhase(Method method, TransactionPhase expected) {
	assertNotNull("Method must not be null", method);
	TransactionalEventListener annotation =
			AnnotatedElementUtils.findMergedAnnotation(method, TransactionalEventListener.class);
	assertEquals("Wrong phase for '" + method + "'", expected, annotation.phase());
}
 
Example 17
Source File: ApplicationListenerMethodAdapter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private static int resolveOrder(Method method) {
	Order ann = AnnotatedElementUtils.findMergedAnnotation(method, Order.class);
	return (ann != null ? ann.value() : 0);
}
 
Example 18
Source File: ArangoQueryMethod.java    From spring-data with Apache License 2.0 4 votes vote down vote up
public Query getQueryAnnotation() {
	return AnnotatedElementUtils.findMergedAnnotation(method, Query.class);
}
 
Example 19
Source File: ParameterAutowireUtils.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Resolve the dependency for the supplied {@link Parameter} from the
 * supplied {@link ApplicationContext}.
 * <p>Provides comprehensive autowiring support for individual method parameters
 * on par with Spring's dependency injection facilities for autowired fields and
 * methods, including support for {@link Autowired @Autowired},
 * {@link Qualifier @Qualifier}, and {@link Value @Value} with support for property
 * placeholders and SpEL expressions in {@code @Value} declarations.
 * <p>The dependency is required unless the parameter is annotated with
 * {@link Autowired @Autowired} with the {@link Autowired#required required}
 * flag set to {@code false}.
 * <p>If an explicit <em>qualifier</em> is not declared, the name of the parameter
 * will be used as the qualifier for resolving ambiguities.
 * @param parameter the parameter whose dependency should be resolved
 * @param parameterIndex the index of the parameter
 * @param containingClass the concrete class that contains the parameter; this may
 * differ from the class that declares the parameter in that it may be a subclass
 * thereof, potentially substituting type variables
 * @param applicationContext the application context from which to resolve the
 * dependency
 * @return the resolved object, or {@code null} if none found
 * @throws BeansException if dependency resolution failed
 * @see #isAutowirable
 * @see Autowired#required
 * @see SynthesizingMethodParameter#forParameter(Parameter)
 * @see AutowireCapableBeanFactory#resolveDependency(DependencyDescriptor, String)
 */
@Nullable
static Object resolveDependency(
		Parameter parameter, int parameterIndex, Class<?> containingClass, ApplicationContext applicationContext) {

	AnnotatedElement annotatedParameter = getEffectiveAnnotatedParameter(parameter, parameterIndex);
	Autowired autowired = AnnotatedElementUtils.findMergedAnnotation(annotatedParameter, Autowired.class);
	boolean required = (autowired == null || autowired.required());

	MethodParameter methodParameter = SynthesizingMethodParameter.forExecutable(
			parameter.getDeclaringExecutable(), parameterIndex);
	DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
	descriptor.setContainingClass(containingClass);
	return applicationContext.getAutowireCapableBeanFactory().resolveDependency(descriptor, null);
}
 
Example 20
Source File: ProfileValueUtils.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * 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
 * @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);
}