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

The following examples show how to use org.springframework.core.annotation.AnnotationUtils#getAnnotation() . 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: ApolloAnnotationProcessor.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
protected void processField(Object bean, String beanName, Field field) {
  ApolloConfig annotation = AnnotationUtils.getAnnotation(field, ApolloConfig.class);
  if (annotation == null) {
    return;
  }

  Preconditions.checkArgument(Config.class.isAssignableFrom(field.getType()),
      "Invalid type: %s for field: %s, should be Config", field.getType(), field);

  String namespace = annotation.value();
  Config config = ConfigService.getConfig(namespace);

  ReflectionUtils.makeAccessible(field);
  ReflectionUtils.setField(field, bean, config);
}
 
Example 2
Source File: AuthCheckerHandlerInterceptor.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void scanCheckAnnos(AnnotatedElement annotatedElement, TagArrayList<Annotation> checkAnnos) {
    Annotation[] annotations = AnnotationUtils.getAnnotations(annotatedElement);
    if (CollectionUtil.isNotEmpty(annotations)) {
        for (Annotation annotation : annotations) {
            //在anno上查找,是否有anno标注为Check
            Check check = AnnotationUtils.getAnnotation(annotation, Check.class);
            if (check != null) {
                Repeatable repeatable = AnnotationUtils.getAnnotation(annotation, Repeatable.class);
                if (repeatable != null) {
                    Class<? extends Annotation> realCheckAnnoClazz = repeatable.value();
                    Set<? extends Annotation> realCheckAnnos = AnnotatedElementUtils.getMergedRepeatableAnnotations(annotatedElement,
                        realCheckAnnoClazz);
                    checkAnnos.addAll(realCheckAnnos);
                } else {
                    checkAnnos.add(annotation);
                }
            }
        }
    }
}
 
Example 3
Source File: AnnotationTypeFilter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
protected Boolean hasAnnotation(String typeName) {
	if (Object.class.getName().equals(typeName)) {
		return false;
	}
	else if (typeName.startsWith("java")) {
		if (!this.annotationType.getName().startsWith("java")) {
			// Standard Java types do not have non-standard annotations on them ->
			// skip any load attempt, in particular for Java language interfaces.
			return false;
		}
		try {
			Class<?> clazz = ClassUtils.forName(typeName, getClass().getClassLoader());
			return ((this.considerMetaAnnotations ? AnnotationUtils.getAnnotation(clazz, this.annotationType) :
					clazz.getAnnotation(this.annotationType)) != null);
		}
		catch (Throwable ex) {
			// Class not regularly loadable - can't determine a match that way.
		}
	}
	return null;
}
 
Example 4
Source File: AbstractMessageConverterMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Validate the binding target if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param parameter the method parameter descriptor
 * @since 4.1.5
 * @see #isBindExceptionRequired
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
	Annotation[] annotations = parameter.getParameterAnnotations();
	for (Annotation ann : annotations) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			binder.validate(validationHints);
			break;
		}
	}
}
 
Example 5
Source File: AbstractMessageConverterMethodArgumentResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate the binding target if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param parameter the method parameter descriptor
 * @since 4.1.5
 * @see #isBindExceptionRequired
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
	Annotation[] annotations = parameter.getParameterAnnotations();
	for (Annotation ann : annotations) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			binder.validate(validationHints);
			break;
		}
	}
}
 
Example 6
Source File: ModelAttributeMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void validateIfApplicable(WebExchangeDataBinder binder, MethodParameter parameter) {
	for (Annotation ann : parameter.getParameterAnnotations()) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			if (hints != null) {
				Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
				binder.validate(validationHints);
			}
			else {
				binder.validate();
			}
		}
	}
}
 
Example 7
Source File: Controllers.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
static boolean isSessionAttributeComplete(Method method) {
    SessionAttributeComplete complete = AnnotationUtils.getAnnotation(method, SessionAttributeComplete.class);
    if (complete != null) {
        return true;
    }
    return false;
}
 
Example 8
Source File: EasySentinelResourceAspect.java    From easy-sentinel with Apache License 2.0 5 votes vote down vote up
@Around("easySentinelResourceAnnotationPointcut()")
public Object invokeResourceWithSentinel(ProceedingJoinPoint pjp) throws Throwable {
    Method method = resolveMethod(pjp);
    EasySentinel easySentinel = AnnotationUtils.getAnnotation(method, EasySentinel.class);
    String resourceName = getResourceName(method);
    if (this.limiter.limiter(easySentinel, resourceName)) {
        BlockException blockException = new BlockException("The current resource access QPS exceeds the maximum limit");
        return handleBlockException(pjp, easySentinel, blockException);
    }
    return method.invoke(pjp.getTarget(), pjp.getArgs());
}
 
Example 9
Source File: MetaAnnotationMethodMatcher.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public boolean matches(Method method, Class targetClass) {
	if (AnnotationUtils.getAnnotation(method, this.annotationType) != null) {
		return true;
	}
	// The method may be on an interface, so let's check on the target class as well.
	Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
	return (specificMethod != method &&
			(AnnotationUtils.getAnnotation(specificMethod, this.annotationType) != null));
}
 
Example 10
Source File: ApiMethodModelsProvider.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private List<ResolvedType> collectAllTypes(RequestMappingContext context, ResolvedMethodParameter parameter) {
    List<ResolvedType> allTypes = newArrayList();
    for (ResolvedType type : collectBindingTypes(context.alternateFor(parameter.getParameterType()), newArrayList())) {
        ApiModel apiModel = AnnotationUtils.getAnnotation(type.getErasedType(), ApiModel.class);
        allTypes.add(type);
        if (apiModel != null) {
            allTypes.addAll(Arrays.stream(apiModel.subTypes())
                    .filter(subType -> subType.getAnnotation(ApiModel.class) != type.getErasedType().getAnnotation(ApiModel.class))
                    .map(typeResolver::resolve).collect(Collectors.toList()));
        }
    }
    return allTypes;
}
 
Example 11
Source File: AnnotationUtilsTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
	AnnotationTest inst = AnnotationUtils.getAnnotation(AnnotationUtilsTest.class, AnnotationTest.class);
	Map<String, Object> attrs = AnnotationUtils.getAnnotationAttributes(inst);
	System.out.println("attrs:"+attrs);
	Assert.assertEquals("test", attrs.get("name"));
}
 
Example 12
Source File: ApolloJsonValueProcessor.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
protected void processMethod(Object bean, String beanName, Method method) {
  ApolloJsonValue apolloJsonValue = AnnotationUtils.getAnnotation(method, ApolloJsonValue.class);
  if (apolloJsonValue == null) {
    return;
  }
  String placeHolder = apolloJsonValue.value();

  Object propertyValue = placeholderHelper
      .resolvePropertyValue(beanFactory, beanName, placeHolder);

  // propertyValue will never be null, as @ApolloJsonValue will not allow that
  if (!(propertyValue instanceof String)) {
    return;
  }

  Type[] types = method.getGenericParameterTypes();
  Preconditions.checkArgument(types.length == 1,
      "Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
      bean.getClass().getName(), method.getName(), method.getParameterTypes().length);

  boolean accessible = method.isAccessible();
  method.setAccessible(true);
  ReflectionUtils.invokeMethod(method, bean, parseJsonValue((String)propertyValue, types[0]));
  method.setAccessible(accessible);

  if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
    Set<String> keys = placeholderHelper.extractPlaceholderKeys(placeHolder);
    for (String key : keys) {
      SpringValue springValue = new SpringValue(key, apolloJsonValue.value(), bean, beanName,
          method, true);
      springValueRegistry.register(beanFactory, key, springValue);
      logger.debug("Monitoring {}", springValue);
    }
  }
}
 
Example 13
Source File: AnnotationManager.java    From qconfig with MIT License 5 votes vote down vote up
public Set<Annotation> getAnnotations(Field field) {
    Set<Annotation> annotations = Sets.newHashSet();
    for (Class<? extends Annotation> annotationClass : loadAnnotations) {
        Annotation annotation = AnnotationUtils.getAnnotation(field, annotationClass);
        if (annotation != null) {
            annotations.add(annotation);
        }
    }
    return annotations;
}
 
Example 14
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Validate the payload if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link Validated},
 * and custom annotations whose name starts with "Valid".
 * @param message the currently processed message
 * @param parameter the method parameter
 * @param target the target payload object
 * @throws MethodArgumentNotValidException in case of binding errors
 */
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
	if (this.validator == null) {
		return;
	}
	for (Annotation ann : parameter.getParameterAnnotations()) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			BeanPropertyBindingResult bindingResult =
					new BeanPropertyBindingResult(target, getParameterName(parameter));
			if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
				((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
			}
			else {
				this.validator.validate(target, bindingResult);
			}
			if (bindingResult.hasErrors()) {
				throw new MethodArgumentNotValidException(message, parameter, bindingResult);
			}
			break;
		}
	}
}
 
Example 15
Source File: MethodJmsListenerEndpoint.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return the default response destination, if any.
 */
protected String getDefaultResponseDestination() {
	Method specificMethod = getMostSpecificMethod();
	SendTo ann = AnnotationUtils.getAnnotation(specificMethod, SendTo.class);
	if (ann != null) {
		Object[] destinations = ann.value();
		if (destinations.length != 1) {
			throw new IllegalStateException("Invalid @" + SendTo.class.getSimpleName() + " annotation on '" +
					specificMethod + "' one destination must be set (got " + Arrays.toString(destinations) + ")");
		}
		return resolve((String) destinations[0]);
	}
	return null;
}
 
Example 16
Source File: QualifierAnnotationAutowireCandidateResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected Annotation getQualifiedElementAnnotation(RootBeanDefinition bd, Class<? extends Annotation> type) {
	AnnotatedElement qualifiedElement = bd.getQualifiedElement();
	return (qualifiedElement != null ? AnnotationUtils.getAnnotation(qualifiedElement, type) : null);
}
 
Example 17
Source File: ClientAsyncRestTemplateClient.java    From documentum-rest-client-java with Apache License 2.0 4 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if("getHeaders".equals(method.getName())) {
        return latestResponse == null ? null : latestResponse.getHeaders();
    }
    if("getStatus".equals(method.getName())) {
        return latestResponse == null ? null : latestResponse.getStatus();
    }
    ClientAsyncOption asyncOption = AnnotationUtils.getAnnotation(method, ClientAsyncOption.class);
    boolean sync = asyncOption != null && (asyncOption.value() || asyncOption.retainClient());
    
    DCTMRestClient client = null;
    if(latestClient == null) {
        client = clientQueue.take();
        if(clientQueue.isEmpty()) {
            if(clientCount.incrementAndGet() <= maxClientCount) {
                clientQueue.put(((AbstractRestTemplateClient)client).clone());
            } else {
                clientCount.decrementAndGet();
            }
        }
    } else {
        client = latestClient;
        latestClient = null;
    }
    if(!sync && (method.getReturnType().isInterface() || method.getReturnType().equals(Void.TYPE))) {
        Response response = new Response();
        executor.execute(new Execution(client, method, args, response));
        Set<Class<?>> interfaces = new HashSet<>();
        interfaces.add(FutureModel.class);
        if(!method.getReturnType().equals(Void.TYPE)) {
            interfaces.add(method.getReturnType());
            Type returnType = method.getGenericReturnType();
            if(returnType instanceof TypeVariable) {
                TypeVariable<?> returnTypeV = (TypeVariable<?>)returnType;
                Type[] genericParameterTypes = method.getGenericParameterTypes();
                for(int i=0;i<genericParameterTypes.length;++i){
                    if(genericParameterTypes[i] instanceof TypeVariable) {
                        TypeVariable<?> paraTypeV = (TypeVariable<?>)genericParameterTypes[i];
                        if(paraTypeV.getName().equals(returnTypeV.getName())) {
                            fillResponseType(interfaces, args[i]);
                            break;
                        }
                    }
                }
            }
        }
        latestResponse = (FutureModel)Proxy.newProxyInstance(DCTMRestClient.class.getClassLoader(), interfaces.toArray(new Class[0]), response);
        return latestResponse;
    } else {
        latestResponse = null;
        try {
            return method.invoke(client, args);
        } finally {
            if(asyncOption != null && asyncOption.retainClient()) {
                latestClient = client;
            } else {
                clientQueue.add(client);
            }
        }
    }
}
 
Example 18
Source File: ProcessStartingMethodInterceptor.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
public Object invoke(MethodInvocation invocation) throws Throwable {

		Method method = invocation.getMethod();

		StartProcess startProcess = AnnotationUtils.getAnnotation(method, StartProcess.class);

		String processKey = startProcess.processKey();

		Assert.hasText(processKey, "you must provide the name of process to start");

		Object result;
		try {
			result = invocation.proceed();
			Map<String, Object> vars = this.processVariablesFromAnnotations(invocation);

			String businessKey = this.processBusinessKey(invocation);

			log.info("variables for the started process: " + vars.toString());

			RuntimeService runtimeService = this.processEngine.getRuntimeService();
			ProcessInstance pi ;
			if (null != businessKey && StringUtils.hasText(businessKey)) {
				pi = runtimeService.startProcessInstanceByKey(processKey, businessKey, vars);
				log.info("the business key for the started process is '" + businessKey + "' ");
			} else {
				pi = runtimeService.startProcessInstanceByKey(processKey, vars);
			}

			String pId = pi.getId();

			if (invocation.getMethod().getReturnType().equals(void.class))
				return null;

			if (shouldReturnProcessInstance(startProcess, invocation, result))
				return pi;

			if (shouldReturnProcessInstanceId(startProcess, invocation, result))
				return pId;

			if (shouldReturnAsyncResultWithProcessInstance(startProcess, invocation, result)) {
				return new AsyncResult<ProcessInstance>(pi);
			}

		} catch (Throwable th) {
			throw new RuntimeException(th);
		}
		return result;
	}
 
Example 19
Source File: QualifierAnnotationAutowireCandidateResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
protected Annotation getFactoryMethodAnnotation(RootBeanDefinition bd, Class<? extends Annotation> type) {
	Method resolvedFactoryMethod = bd.getResolvedFactoryMethod();
	return (resolvedFactoryMethod != null ? AnnotationUtils.getAnnotation(resolvedFactoryMethod, type) : null);
}
 
Example 20
Source File: RequiredAnnotationBeanPostProcessor.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Is the supplied property required to have a value (that is, to be dependency-injected)?
 * <p>This implementation looks for the existence of a
 * {@link #setRequiredAnnotationType "required" annotation}
 * on the supplied {@link PropertyDescriptor property}.
 * @param propertyDescriptor the target PropertyDescriptor (never {@code null})
 * @return {@code true} if the supplied property has been marked as being required;
 * {@code false} if not, or if the supplied property does not have a setter method
 */
protected boolean isRequiredProperty(PropertyDescriptor propertyDescriptor) {
	Method setter = propertyDescriptor.getWriteMethod();
	return (setter != null && AnnotationUtils.getAnnotation(setter, getRequiredAnnotationType()) != null);
}