下面列出了org.springframework.core.annotation.AnnotationUtils#getAnnotation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
}
}
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);
}
}
}
}
}
@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;
}
@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);
}
@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"));
}
/**
* 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;
}
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;
}
@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);
}
}
}
/**
* 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;
}
}
}
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;
}
@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));
}
@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());
}
/**
* {@inheritDoc}
*/
static boolean isSessionAttributeComplete(Method method) {
SessionAttributeComplete complete = AnnotationUtils.getAnnotation(method, SessionAttributeComplete.class);
if (complete != null) {
return true;
}
return false;
}
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();
}
}
}
}
/**
* 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;
}
}
}
protected Annotation getFactoryMethodAnnotation(RootBeanDefinition bd, Class<? extends Annotation> type) {
Method resolvedFactoryMethod = bd.getResolvedFactoryMethod();
return (resolvedFactoryMethod != null ? AnnotationUtils.getAnnotation(resolvedFactoryMethod, type) : null);
}
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;
}
protected Annotation getQualifiedElementAnnotation(RootBeanDefinition bd, Class<? extends Annotation> type) {
AnnotatedElement qualifiedElement = bd.getQualifiedElement();
return (qualifiedElement != null ? AnnotationUtils.getAnnotation(qualifiedElement, type) : null);
}
@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);
}
}
}
}
/**
* 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);
}