Java Code Examples for org.springframework.core.annotation.AnnotationUtils#findAnnotation()

The following examples show how to use org.springframework.core.annotation.AnnotationUtils#findAnnotation() . 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: BeanConfigFactoryManager.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <BeanType> void postConstruct(final ConfiguredBean bean) {
	if (bean == null) {
		return;
	}
	final PostConstructed pc = AnnotationUtils.findAnnotation(bean.getClass(), PostConstructed.class);
	if (bean instanceof BeanPostConstructor<?>
			&& (pc == null || !mappedPostConstrucors.containsKey(bean.getClass()))) {
		((BeanPostConstructor) bean).postConstruct(bean, this);
	}
	if (pc != null) {
		final BeanPostConstructor bpc = mappedPostConstrucors.get(pc.constructor());
		if (bpc != null) {
			bpc.postConstruct(bean, this);
		} else {
			logger.error("Unsatisfied bean construction of '{}' due to missing post constructor of type: {}", bean,
					pc.getClass());
		}
	}
	configInjector.postProcessBeforeInitialization(bean, bean.getClass().getName());
}
 
Example 2
Source File: AMethod.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * Get the IbisDoc values of the referred method in IbisDocRef
 *
 * @param className - The full name of the class
 * @param methodName - The method name
 * @return the IbisDoc of the method
 */
public IbisDoc getRefValues(String className, String methodName) {

    IbisDoc ibisDoc = null;
    try {
        Class parentClass = Class.forName(className);
        for (Method parentMethod : parentClass.getDeclaredMethods()) {
            if (parentMethod.getName().equals(methodName)) {

                // Get the IbisDoc values of that method
                ibisDoc = AnnotationUtils.findAnnotation(parentMethod, IbisDoc.class);
                break;
            }
        }

    } catch (ClassNotFoundException e) {
        LOGGER.warn("Super class [" + e +  "] was not found!");
    }

    return ibisDoc;
}
 
Example 3
Source File: MetaAnnotationUtilsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void findAnnotationDescriptorForClassWithMetaAnnotatedInterface() {
	Component rawAnnotation = AnnotationUtils.findAnnotation(ClassWithMetaAnnotatedInterface.class, Component.class);
	AnnotationDescriptor<Component> descriptor =
			findAnnotationDescriptor(ClassWithMetaAnnotatedInterface.class, Component.class);

	assertNotNull(descriptor);
	assertEquals(ClassWithMetaAnnotatedInterface.class, descriptor.getRootDeclaringClass());
	assertEquals(Meta1.class, descriptor.getDeclaringClass());
	assertEquals(rawAnnotation, descriptor.getAnnotation());
	assertEquals(Meta1.class, descriptor.getComposedAnnotation().annotationType());
}
 
Example 4
Source File: RestUrlParserTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String checkAndReturnPath(Optional<Class<?>> endpointClass) {
    Path controllerPathAnnotation = AnnotationUtils.findAnnotation(endpointClass.get(), Path.class);
    if (controllerPathAnnotation == null) {
        fail("Can not find Path annotation for this controller: " + endpointClass.get().getSimpleName());
    }
    return controllerPathAnnotation.value();
}
 
Example 5
Source File: RateLimiterAspect.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Around("rateLimit()")
public Object pointcut(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
    RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
    if (rateLimiter != null) {
        String key = rateLimiter.key();
        // 默认用类名+方法名做限流的 key 前缀
        if (StrUtil.isBlank(key)) {
            key = method.getDeclaringClass().getName()+StrUtil.DOT+method.getName();
        }
        // 最终限流的 key 为 前缀 + IP地址
        // TODO: 此时需要考虑局域网多用户访问的情况,因此 key 后续需要加上方法参数更加合理
        key = key + SEPARATOR + IpUtil.getIpAddr();

        long max = rateLimiter.max();
        long timeout = rateLimiter.timeout();
        TimeUnit timeUnit = rateLimiter.timeUnit();
        boolean limited = shouldLimited(key, max, timeout, timeUnit);
        if (limited) {
            throw new RuntimeException("手速太快了,慢点儿吧~");
        }
    }

    return point.proceed();
}
 
Example 6
Source File: AopUtils.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static <T extends Annotation> T findMethodAnnotation(Class targetClass, Method method, Class<T> annClass) {
    Method m = method;
    T a = AnnotationUtils.findAnnotation(m, annClass);
    if (a != null) {
        return a;
    }
    m = ClassUtils.getMostSpecificMethod(m, targetClass);
    a = AnnotationUtils.findAnnotation(m, annClass);
    if (a == null) {
        List<Class> supers = new ArrayList<>();
        supers.addAll(Arrays.asList(targetClass.getInterfaces()));
        if (targetClass.getSuperclass() != Object.class) {
            supers.add(targetClass.getSuperclass());
        }

        for (Class aClass : supers) {
            if(aClass==null){
                continue;
            }
            Method ims[] = new Method[1];

            ReflectionUtils.doWithMethods(aClass, im -> {
                if (im.getName().equals(method.getName()) && im.getParameterCount() == method.getParameterCount()) {
                    ims[0] = im;
                }
            });

            if (ims[0] != null) {
                a = findMethodAnnotation(aClass, ims[0], annClass);
                if (a != null) {
                    return a;
                }
            }
        }
    }
    return a;
}
 
Example 7
Source File: RepositoryUtils.java    From spring-content with Apache License 2.0 5 votes vote down vote up
public static String repositoryPath(RepositoryInformation info) {
	Class<?> clazz = info.getRepositoryInterface();
	RepositoryRestResource annotation = AnnotationUtils.findAnnotation(clazz,
			RepositoryRestResource.class);
	String path = annotation == null ? null : annotation.path().trim();
	path = StringUtils.hasText(path) ? path : English
			.plural(StringUtils.uncapitalize(info.getDomainType().getSimpleName()));
	return path;
}
 
Example 8
Source File: ExceptionTranslator.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDTO> processRuntimeException(Exception ex) throws Exception {
    BodyBuilder builder;
    ErrorDTO errorDTO;
    ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
    if (responseStatus != null) {
        builder = ResponseEntity.status(responseStatus.value());
        errorDTO = new ErrorDTO("error." + responseStatus.value().value(), responseStatus.reason());
    } else {
        builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        errorDTO = new ErrorDTO(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error");
    }
    return builder.body(errorDTO);
}
 
Example 9
Source File: PropertyDataProcessor.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
private void addMethodSagaTask(final Method method) {
    SagaTask sagaTask = AnnotationUtils.findAnnotation(method, SagaTask.class);
    if (sagaTask != null) {
        PropertySagaTask task = new PropertySagaTask(sagaTask.code(), sagaTask.description(),
                sagaTask.sagaCode(), sagaTask.seq(), sagaTask.maxRetryCount());
        task.setConcurrentLimitNum(sagaTask.concurrentLimitNum());
        task.setConcurrentLimitPolicy(sagaTask.concurrentLimitPolicy().name());
        task.setTimeoutPolicy(sagaTask.timeoutPolicy().name());
        task.setTimeoutSeconds(sagaTask.timeoutSeconds());
        addOutputSchema(sagaTask, method, task);
        propertyData.addSagaTask(task);
    }
}
 
Example 10
Source File: ExceptionTranslator.java    From tutorials with MIT License 5 votes vote down vote up
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) {
    BodyBuilder builder;
    ErrorVM errorVM;
    ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
    if (responseStatus != null) {
        builder = ResponseEntity.status(responseStatus.value());
        errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason());
    } else {
        builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error");
    }
    return builder.body(errorVM);
}
 
Example 11
Source File: AnnotatedStoreEventInvoker.java    From spring-content with Apache License 2.0 5 votes vote down vote up
<H extends Annotation, E> void findHandler(Object bean, Method method,
		Class<H> handler, Class<? extends StoreEvent> eventType) {
	H annotation = AnnotationUtils.findAnnotation(method, handler);

	if (annotation == null) {
		return;
	}

	Class<?>[] parameterTypes = method.getParameterTypes();

	if (parameterTypes.length == 0) {
		throw new IllegalStateException(String.format(
				"Event handler method %s must have a content object argument",
				method.getName()));
	}

	EventHandlerMethod handlerMethod = new EventHandlerMethod(parameterTypes[0], bean,
			method);

	logger.debug(
			String.format("Annotated handler method found: {%s}", handlerMethod));

	List<EventHandlerMethod> events = handlerMethods.get(eventType);

	if (events == null) {
		events = new ArrayList<>();
	}

	if (events.isEmpty()) {
		handlerMethods.add(eventType, handlerMethod);
		return;
	}

	events.add(handlerMethod);
	Collections.sort(events);
	handlerMethods.put(eventType, events);
}
 
Example 12
Source File: ApiTestBase.java    From iaf with Apache License 2.0 5 votes vote down vote up
public void checkContextFields(M resource) {
	for(Field field : resource.getClass().getDeclaredFields()) {
		Context context = AnnotationUtils.findAnnotation(field, Context.class); //Injected JAX-WS Resources

		if(context != null && field.getType().isAssignableFrom(Request.class)) {
			Request request = new MockHttpRequest();
			try {
				field.set(resource, request);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
				fail("unable to inject Request");
			}
		}
	}
}
 
Example 13
Source File: ReflectionUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private static boolean isAnyAnnotationPresent(Method method, Class<? extends Annotation>[] annotations) {
    for (Class<? extends Annotation> annotation : annotations) {
        if (AnnotationUtils.findAnnotation(method, annotation) != null) {
            return true;
        }
    }
    return false;
}
 
Example 14
Source File: AnnotationJmxAttributeSource.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public org.springframework.jmx.export.metadata.ManagedMetric getManagedMetric(Method method) throws InvalidMetadataException {
	ManagedMetric ann = AnnotationUtils.findAnnotation(method, ManagedMetric.class);
	return copyPropertiesToBean(ann, org.springframework.jmx.export.metadata.ManagedMetric.class);
}
 
Example 15
Source File: RateLimiterAopAdvisor.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(Method method, Class<?> targetClass) {

    return AnnotationUtils.findAnnotation(method, RateLimiter.class) != null
            || AnnotationUtils.findAnnotation(targetClass, RateLimiter.class) != null;
}
 
Example 16
Source File: AnnotationExceptionHandlerMethodResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(Method method) {
	return AnnotationUtils.findAnnotation(method, MessageExceptionHandler.class) != null;
}
 
Example 17
Source File: StopWatchAdvice.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Around advice that logs methods times for all service methods.
 *
 * @param pjp the proceeding join point.
 *
 * @return the return value of the method we are advising.
 * @throws Throwable if there were any problems executing the method.
 */
@Around("serviceMethods()")
public Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable
{
    // Get the target class being called.
    Class<?> targetClass = pjp.getTarget().getClass();

    // Get the target method being called.
    MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSignature.getMethod();
    if (targetMethod.getDeclaringClass().isInterface())
    {
        // Get the underlying implementation if we are given an interface.
        targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), targetMethod.getParameterTypes());
    }

    // Only keep a stop watch if the class and method aren't suppressing logging and the log level is info.
    if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null) &&
        (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null) && (LOGGER.isInfoEnabled()))
    {
        // Start the stop watch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Proceed to the join point (i.e. call the method and let it return).
        Object returnValue = pjp.proceed();

        // Log the duration.
        long durationMilliseconds = stopWatch.getTime();
        LOGGER.info("javaMethod=\"{}.{}\" javaMethodDurationTimeInMilliseconds={} javaMethodDurationTimeFormatted=\"{}\"", targetClass.getName(),
            targetMethodSignature.getName(), durationMilliseconds, HerdDateUtils.formatDuration(durationMilliseconds));

        // Return the method return value.
        return returnValue;
    }
    else
    {
        // Invoke the method normally.
        return pjp.proceed();
    }
}
 
Example 18
Source File: AbstractTestContextBootstrapper.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public final MergedContextConfiguration buildMergedContextConfiguration() {
	Class<?> testClass = getBootstrapContext().getTestClass();
	CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate = getCacheAwareContextLoaderDelegate();

	if (MetaAnnotationUtils.findAnnotationDescriptorForTypes(
			testClass, ContextConfiguration.class, ContextHierarchy.class) == null) {
		return buildDefaultMergedContextConfiguration(testClass, cacheAwareContextLoaderDelegate);
	}

	if (AnnotationUtils.findAnnotation(testClass, ContextHierarchy.class) != null) {
		Map<String, List<ContextConfigurationAttributes>> hierarchyMap =
				ContextLoaderUtils.buildContextHierarchyMap(testClass);
		MergedContextConfiguration parentConfig = null;
		MergedContextConfiguration mergedConfig = null;

		for (List<ContextConfigurationAttributes> list : hierarchyMap.values()) {
			List<ContextConfigurationAttributes> reversedList = new ArrayList<>(list);
			Collections.reverse(reversedList);

			// Don't use the supplied testClass; instead ensure that we are
			// building the MCC for the actual test class that declared the
			// configuration for the current level in the context hierarchy.
			Assert.notEmpty(reversedList, "ContextConfigurationAttributes list must not be empty");
			Class<?> declaringClass = reversedList.get(0).getDeclaringClass();

			mergedConfig = buildMergedContextConfiguration(
					declaringClass, reversedList, parentConfig, cacheAwareContextLoaderDelegate, true);
			parentConfig = mergedConfig;
		}

		// Return the last level in the context hierarchy
		Assert.state(mergedConfig != null, "No merged context configuration");
		return mergedConfig;
	}
	else {
		return buildMergedContextConfiguration(testClass,
				ContextLoaderUtils.resolveContextConfigurationAttributes(testClass),
				null, cacheAwareContextLoaderDelegate, true);
	}
}
 
Example 19
Source File: AopContextHolder.java    From Milkomeda with MIT License 4 votes vote down vote up
/**
 * 获取处理组件元数据
 * @param handlerAnnotationClazz    处理器注解类
 * @param executeAnnotationClazz    执行方法注解类
 * @param nameProvider              标识名称提供函数
 * @param onlyOneExecutorPerHandler 一个组件只有一个处理方法是传true
 * @return  Map
 */
public static Map<String, List<HandlerMetaData>> getHandlerMetaData(
        Class<? extends Annotation> handlerAnnotationClazz,
        Class<? extends Annotation> executeAnnotationClazz,
        BiFunction<Annotation, HandlerMetaData, String> nameProvider,
        boolean onlyOneExecutorPerHandler) {
    Map<String, List<HandlerMetaData>> handlerMap = new HashMap<>();
    Map<String, Object> beanMap = ApplicationContextHolder.get().getBeansWithAnnotation(handlerAnnotationClazz);
    for (String key : beanMap.keySet()) {
        Object target = beanMap.get(key);
        // 查找AOP切面(通过Proxy.isProxyClass()判断类是否是代理的接口类,AopUtils.isAopProxy()判断对象是否被代理),可以通过AopUtils.getTargetClass()获取原Class
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(AopUtils.isAopProxy(target) ?
                AopUtils.getTargetClass(target) : target.getClass());
        for (Method method : methods) {
            // 获取指定方法上的注解的属性
            final Annotation executeAnnotation = AnnotationUtils.findAnnotation(method, executeAnnotationClazz);
            if (null == executeAnnotation) {
                continue;
            }
            HandlerMetaData metaData = new HandlerMetaData();
            // 支持SpEL
            String name = nameProvider.apply(executeAnnotation, metaData);
            if (name.startsWith("'") || name.startsWith("@") || name.startsWith("#") || name.startsWith("T(") || name.startsWith("args[")) {
                name = ELContext.getValue(target, new Object[]{}, target.getClass(), method, name, String.class);
            }
            if (name == null) {
                throw new IllegalArgumentException("Please specify the [tag] of "+ executeAnnotation +" !");
            }
            metaData.setName(name);
            metaData.setTarget(target);
            metaData.setMethod(method);
            if (handlerMap.containsKey(name)) {
                handlerMap.get(name).add(metaData);
            } else {
                List<HandlerMetaData> list = new ArrayList<>();
                list.add(metaData);
                handlerMap.put(name, list);
            }
            // 如果一个组件只会有一个处理方法,直接返回
            if (onlyOneExecutorPerHandler) {
                break;
            }
        }
    }
    return handlerMap;
}
 
Example 20
Source File: ReflectionHelper.java    From cm_ext with Apache License 2.0 2 votes vote down vote up
/**
 * Finds the annotation of the provided method by searching
 * the entire method hierarchy.
 *
 * @param method the method.
 * @param annotationType the annotation class.
 * @param <A> the annotation type.
 * @return the annotation if it is found. Null otherwise.
 */
@Nullable
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
  return AnnotationUtils.findAnnotation(method, annotationType);
}