类org.springframework.core.annotation.AnnotationUtils源码实例Demo

下面列出了怎么用org.springframework.core.annotation.AnnotationUtils的API类实例代码及写法,或者点击链接到github查看源代码。

/**
 * 创建匹配条件
 *
 * @param clazz
 * @return
 */
private static RequestCondition<ApiVersionCondition> createCondition(Class<?> clazz) {
    RequestMapping classRequestMapping = AnnotationUtils.findAnnotation(clazz, RequestMapping.class);
    if (classRequestMapping == null) {
        return null;
    }
    StringBuilder mappingUrlBuilder = new StringBuilder();
    if (classRequestMapping.value().length > 0) {
        mappingUrlBuilder.append(classRequestMapping.value()[0]);
    }
    String mappingUrl = mappingUrlBuilder.toString();
    if (!mappingUrl.contains("{version}") || !mappingUrl.contains("{v}")) {
        return null;
    }
    ApiVersion apiVersion = AnnotationUtils.findAnnotation(clazz, ApiVersion.class);
    return apiVersion == null ? new ApiVersionCondition(1) : new ApiVersionCondition(apiVersion.value());
}
 
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
    if (this.nonAnnotatedClasses.contains(targetClass)) return bean;
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
    if (methods == null) return bean;
    for (Method method : methods) {
        DcsScheduled dcsScheduled = AnnotationUtils.findAnnotation(method, DcsScheduled.class);
        if (null == dcsScheduled || 0 == method.getDeclaredAnnotations().length) continue;
        List<ExecOrder> execOrderList = Constants.execOrderMap.computeIfAbsent(beanName, k -> new ArrayList<>());
        ExecOrder execOrder = new ExecOrder();
        execOrder.setBean(bean);
        execOrder.setBeanName(beanName);
        execOrder.setMethodName(method.getName());
        execOrder.setDesc(dcsScheduled.desc());
        execOrder.setCron(dcsScheduled.cron());
        execOrder.setAutoStartup(dcsScheduled.autoStartup());
        execOrderList.add(execOrder);
        this.nonAnnotatedClasses.add(targetClass);
    }
    return bean;
}
 
@Override
public void doVisitEnd(Class<?> annotationClass) {
	super.doVisitEnd(annotationClass);
	List<AnnotationAttributes> attributes = this.attributesMap.get(this.annotationType);
	if (attributes == null) {
		this.attributesMap.add(this.annotationType, this.attributes);
	}
	else {
		attributes.add(0, this.attributes);
	}
	Set<String> metaAnnotationTypeNames = new LinkedHashSet<String>();
	Annotation[] metaAnnotations = AnnotationUtils.getAnnotations(annotationClass);
	if (!ObjectUtils.isEmpty(metaAnnotations)) {
		for (Annotation metaAnnotation : metaAnnotations) {
			if (!AnnotationUtils.isInJavaLangAnnotationPackage(metaAnnotation)) {
				recursivelyCollectMetaAnnotations(metaAnnotationTypeNames, metaAnnotation);
			}
		}
	}
	if (this.metaAnnotationMap != null) {
		this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames);
	}
}
 
源代码4 项目: citrus-admin   文件: ConfigurationProvider.java
/**
 * Enriches configuration instance with system properties and/or environment variables as field value when applicable.
 *
 * @param configuration
 * @param <T>
 * @return
 */
public static <T> T load(final T configuration) {
    SystemConfigurable systemConfigurable = AnnotationUtils.findAnnotation(configuration.getClass(), SystemConfigurable.class);

    ReflectionUtils.doWithFields(configuration.getClass(), field -> {
        if (field.getAnnotation(SystemProperty.class) != null) {
            SystemProperty systemProperty = field.getAnnotation(SystemProperty.class);
            Method setter = ReflectionUtils.findMethod(configuration.getClass(), "set" + StringUtils.capitalize(field.getName()), field.getType());

            if (setter != null) {
                if (StringUtils.hasText(systemProperty.name())) {
                    ReflectionUtils.invokeMethod(setter, configuration, System.getProperty((systemConfigurable != null ? systemConfigurable.prefix() : "") + systemProperty.name(), Optional.ofNullable(System.getenv((systemConfigurable != null ? systemConfigurable.environmentPrefix() : "") + systemProperty.environment()))
                            .orElse(getDefaultValue(configuration.getClass(), field, systemProperty, configuration))));
                } else if (StringUtils.hasText(systemProperty.environment())) {
                    ReflectionUtils.invokeMethod(setter, configuration, Optional.ofNullable(System.getenv((systemConfigurable != null ? systemConfigurable.environmentPrefix() : "") + systemProperty.environment()))
                            .orElse(getDefaultValue(configuration.getClass(), field, systemProperty, configuration)));
                } else {
                    ReflectionUtils.invokeMethod(setter, configuration, getDefaultValue(configuration.getClass(), field, systemProperty, configuration));
                }
            }
        }
    });

    return configuration;
}
 
源代码5 项目: haven-platform   文件: NodeMapping.java
private void saveType(String path, T object, KeyValueStorage storage) {
    Class<?> clazz = object.getClass();
    String name = PROP_TYPE;
    String value = clazz.getName();
    JsonTypeInfo typeInfo = AnnotationUtils.findAnnotation(clazz, JsonTypeInfo.class);
    if (typeInfo != null && !clazz.equals(typeInfo.defaultImpl())) {
        JsonTypeInfo.As include = typeInfo.include();
        if(include != JsonTypeInfo.As.PROPERTY &&
           include != JsonTypeInfo.As.EXTERNAL_PROPERTY /* it for capability with jackson oddities */) {
            throw new IllegalArgumentException("On " + clazz + " mapping support only " + JsonTypeInfo.As.PROPERTY + " but find: " + include);
        }
        name = getPropertyName(typeInfo);
        value = getJsonType(clazz, typeInfo);
    }
    storage.set(KvUtils.join(path, name), value);
}
 
源代码6 项目: eclair   文件: AnnotationExtractorTest.java
@Test
public void synthesizeLogOut() {
    // given
    Map<String, Object> attributes = new HashMap<>();
    attributes.put("level", ERROR);
    attributes.put("ifEnabled", WARN);
    attributes.put("verbose", INFO);
    attributes.put("printer", "printer");
    attributes.put("logger", "logger");
    Log log = AnnotationUtils.synthesizeAnnotation(attributes, Log.class, null);
    // when
    Log.out logOut = annotationExtractor.synthesizeLogOut(log);
    // then
    assertThat(logOut.level(), is(ERROR));
    assertThat(logOut.ifEnabled(), is(WARN));
    assertThat(logOut.verbose(), is(INFO));
    assertThat(logOut.printer(), is("printer"));
    assertThat(logOut.logger(), is("logger"));
}
 
/**
 * 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;
		}
	}
}
 
源代码8 项目: HotswapAgent   文件: ResetSpringStaticCaches.java
private static void resetAnnotationUtilsCache() {
    ReflectionHelper.invokeNoException(null, "org.springframework.core.annotation.AnnotationUtils",
            ResetSpringStaticCaches.class.getClassLoader(), "clearCache", new Class<?>[] {});

    Map annotatedInterfaceCache = (Map) ReflectionHelper.getNoException(null, AnnotationUtils.class,
            "annotatedInterfaceCache");
    if (annotatedInterfaceCache != null) {
        annotatedInterfaceCache.clear();
        LOGGER.trace("Cache cleared: AnnotationUtils.annotatedInterfaceCache");
    } else {
        LOGGER.trace("Cache NOT cleared: AnnotationUtils.annotatedInterfaceCache not exists in target Spring verion (pre 3.1.x)");
    }

    Map findAnnotationCache = (Map) ReflectionHelper.getNoException(null, AnnotationUtils.class, "findAnnotationCache");
    if (findAnnotationCache != null) {
        findAnnotationCache.clear();
        LOGGER.trace("Cache cleared: AnnotationUtils.findAnnotationCache");
    } else {
        LOGGER.trace("Cache NOT cleared: AnnotationUtils.findAnnotationCache not exists in target Spring version (pre 4.1)");
    }

}
 
@SuppressWarnings({"Duplicates"})
@Override
protected void initializeAnnotation(Method method) throws InvalidAggregationQueryException {
  this.aggregateAnnotation = method.getAnnotation(Aggregate.class);
  Class inputType = aggregateAnnotation.inputType();
  this.collectionName = deriveCollectionName(aggregateAnnotation,
                                             (idx) -> mongoParameterAccessor.getValues()[idx].toString(),
                                             () -> {
                                               Document documentAnnotation = AnnotationUtils.findAnnotation(inputType,
                                                                                                            Document.class);
                                               return documentAnnotation != null ? documentAnnotation.collection() : null;
                                             },
                                             (s) -> {
                                               Expression expression = detectExpression(s);
                                               if (expression != null) {
                                                 return expression.getValue(context, String.class);
                                               }
                                               return s;
                                             });
  this.placeholderRepFn = (q) -> replacePlaceholders((String) q);
  // set queryProcessorFactory here - the base class calls createQuery which needs the factory.
  this.queryProcessorFactory = new DefaultPipelineStageQueryProcessorFactory();
}
 
源代码10 项目: alfresco-remote-api   文件: ResourceInspector.java
/**
 * Inspects the resource to determine what api it belongs to.
 * It does this by looking for the WebApi package annotation.
 * 
 * @return Api
 */
public static Api inspectApi(Class<?> resource)
{
    Package myPackage = resource.getPackage();
    Annotation annot = myPackage.getAnnotation(WebApi.class);
  
    if (annot != null)
    {
        Map<String, Object> annotAttribs =  AnnotationUtils.getAnnotationAttributes(annot);
        String apiName = String.valueOf(annotAttribs.get("name"));
        String apiScope = String.valueOf(annotAttribs.get("scope"));
        String apiVersion = String.valueOf(annotAttribs.get("version"));
        return Api.valueOf(apiName, apiScope, apiVersion);
    }
    return null;
}
 
@Test
// Test for SPR-6268
public void testRefreshableFromTagProxyTargetClass() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml",
			getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals("Hello World!", messenger.getMessage());

	assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger));

	// Check that AnnotationUtils works with concrete proxied script classes
	assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class));
}
 
/**
 * Find a {@link Annotation} of {@code annotationType} on the specified
 * bean, traversing its interfaces and super classes if no annotation can be
 * found on the given class itself, as well as checking its raw bean class
 * if not found on the exposed bean reference (e.g. in case of a proxy).
 */
@Override
@Nullable
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
		throws NoSuchBeanDefinitionException {

	A ann = null;
	Class<?> beanType = getType(beanName);
	if (beanType != null) {
		ann = AnnotationUtils.findAnnotation(beanType, annotationType);
	}
	if (ann == null && containsBeanDefinition(beanName)) {
		BeanDefinition bd = getMergedBeanDefinition(beanName);
		if (bd instanceof AbstractBeanDefinition) {
			AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
			if (abd.hasBeanClass()) {
				Class<?> beanClass = abd.getBeanClass();
				if (beanClass != beanType) {
					ann = AnnotationUtils.findAnnotation(beanClass, annotationType);
				}
			}
		}
	}
	return ann;
}
 
@Test  // SPR-6268
public void testRefreshableFromTagProxyTargetClass() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml",
			getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals("Hello World!", messenger.getMessage());

	assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger));

	// Check that AnnotationUtils works with concrete proxied script classes
	assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class));
}
 
源代码14 项目: iaf   文件: AMethod.java
/**
 * 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;
}
 
源代码15 项目: openemm   文件: ReflectionTableParser.java
private Map<String, String> getRowColumnsFromObjectFields(Object object) {
    Class<?> clazz = object.getClass();
    if (Objects.isNull(AnnotationUtils.findAnnotation(clazz, textTableClass))) {
        return Collections.emptyMap();
    }

    Map<String, String> columns = new LinkedHashMap<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(textColumnClass)) {
            TextColumn textColumn = field.getAnnotation(textColumnClass);
            String columnKey = StringUtils.defaultIfEmpty(textColumn.key(), field.getName());
            columns.put(columnKey, getColumnValueFromField(field, object));
        }
    }

    return columns;
}
 
/**
 * Validate the payload 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 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;
		}
	}
}
 
/**
 * Lookup for {@link SerializableProxy} annotation on fields or methods and 
 * replace value with a Serializable proxy.
 */
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {
	
	List<AnnotatedElement> elements = AnnotatedElementAccessor.findAnnotatedElements(SerializableProxy.class, bean.getClass());
	
	for (AnnotatedElement element : elements) {
		ResolvableType type = getResolvableType(element);
		Object value = AnnotatedElementAccessor.getValue(element, bean);
		if (value != null && !(value instanceof SerializableAopProxy)) {
			SerializableProxy ann = AnnotationUtils.getAnnotation(element, SerializableProxy.class);
			boolean proxyTargetClass = !type.resolve().isInterface() || ann.proxyTargetClass();
			Object proxy = getProxy(value, proxyTargetClass, ann.useCache(), 
					getDependencyDescriptor(element), beanName);
			if (proxy != null)
				AnnotatedElementAccessor.setValue(element, bean, proxy);
		}	
	}
	
	return bean;
}
 
源代码18 项目: raptor   文件: RaptorClientPostProcessor.java
private Object getClientProxy(Class<?> interfaceClass) {
    RaptorInterface raptorInterface = AnnotationUtils.findAnnotation(interfaceClass, RaptorInterface.class);
    if (raptorInterface == null) {
        return null;
    }
    Object clientProxy = this.raptorClientRegistry.get(interfaceClass);
    if (clientProxy != null) {
        return clientProxy;
    }
    List<RaptorClientFactory> factories = this.raptorClientFactories.getIfAvailable();
    for (RaptorClientFactory raptorClientFactory : factories) {
        if (raptorClientFactory.support(interfaceClass)) {
            clientProxy = raptorClientFactory.create(interfaceClass);
            this.raptorClientRegistry.registerClientProxy(interfaceClass, clientProxy);
            break;
        }
    }
    return clientProxy;
}
 
@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;
}
 
源代码20 项目: haven-platform   文件: NodeMapping.java
@SuppressWarnings("unchecked")
private <S> Class<S> resolveJsonType(String path, Class<S> type) {
    JsonTypeInfo typeInfo = AnnotationUtils.findAnnotation(type, JsonTypeInfo.class);
    if (typeInfo == null) {
        return null;
    }
    String property = getPropertyName(typeInfo);
    String proppath = KvUtils.join(path, property);
    try {
        KvNode node = getStorage().get(proppath);
        if(node == null) {
            return null;
        }
        String str = node.getValue();
        JsonSubTypes subTypes = AnnotationUtils.findAnnotation(type, JsonSubTypes.class);
        for (JsonSubTypes.Type t : subTypes.value()) {
            if (t.name().equals(str)) {
                return (Class<S>) t.value();
            }
        }
    } catch (Exception e) {
        log.error("can't instantiate class", e);
    }
    return null;
}
 
源代码21 项目: citrus-admin   文件: ConfigurationProvider.java
/**
 * Applies configuration to system properties setting {@link SystemProperty} annotated fields as system properties.
 * @param configurationHolder
 */
public static void apply(Object configurationHolder) {
    SystemConfigurable systemConfigurable = AnnotationUtils.findAnnotation(configurationHolder.getClass(), SystemConfigurable.class);
    
    ReflectionUtils.doWithFields(configurationHolder.getClass(), field -> {
        if (field.getAnnotation(SystemProperty.class) != null) {
            SystemProperty configProperty = field.getAnnotation(SystemProperty.class);
            if (StringUtils.hasText(configProperty.name())) {
                Method getter = ReflectionUtils.findMethod(configurationHolder.getClass(), "get" + StringUtils.capitalize(field.getName()));
                if (getter != null) {
                    System.setProperty((systemConfigurable != null ? systemConfigurable.prefix() : "") + configProperty.name(), String.valueOf(ReflectionUtils.invokeMethod(getter, configurationHolder)));
                }
            }
        }
    });
}
 
源代码22 项目: BlogManagePlatform   文件: DefaultRequiredPlugin.java
private void resolveAnnotatedElement(ModelPropertyContext context) {
	AnnotatedElement annotated = context.getAnnotatedElement().orNull();
	if (annotated == null) {
		return;
	}
	if (AnnotationUtils.findAnnotation(annotated, NotNull.class) != null) {
		context.getBuilder().required(true);
	} else if (AnnotationUtils.findAnnotation(annotated, NotEmpty.class) != null) {
		context.getBuilder().required(true);
	} else if (AnnotationUtils.findAnnotation(annotated, NotBlank.class) != null) {
		context.getBuilder().required(true);
	} else {
		ApiModelProperty annotation = AnnotationUtils.findAnnotation(annotated, ApiModelProperty.class);
		if (annotation != null && annotation.required()) {
			//如果ApiModelProperty上强制要求required为true,则为true
			context.getBuilder().required(true);
		} else {
			context.getBuilder().required(false);
		}
	}
}
 
/**
 * Utility operation to return an array of configuration classes defined in
 * {@link EnableBinding} annotation. Typically used for tests that do not rely on
 * creating an SCSt boot application annotated with {@link EnableBinding}, yet require
 * full {@link Binder} configuration.
 * @param additionalConfigurationClasses config classes to be added to the default
 * config
 * @return an array of configuration classes defined in {@link EnableBinding}
 * annotation
 */
public static Class<?>[] getCompleteConfiguration(
		Class<?>... additionalConfigurationClasses) {
	List<Class<?>> configClasses = new ArrayList<>();
	configClasses.add(TestChannelBinderConfiguration.class);
	Import annotation = AnnotationUtils.getAnnotation(EnableBinding.class,
			Import.class);
	Map<String, Object> annotationAttributes = AnnotationUtils
			.getAnnotationAttributes(annotation);
	configClasses
			.addAll(Arrays.asList((Class<?>[]) annotationAttributes.get("value")));
	configClasses.add(BindingServiceConfiguration.class);
	if (additionalConfigurationClasses != null) {
		configClasses.addAll(Arrays.asList(additionalConfigurationClasses));
	}
	return configClasses.toArray(new Class<?>[] {});
}
 
protected String[] getTargetDestinations(@Nullable Annotation annotation, Message<?> message, String defaultPrefix) {
	if (annotation != null) {
		String[] value = (String[]) AnnotationUtils.getValue(annotation);
		if (!ObjectUtils.isEmpty(value)) {
			return value;
		}
	}

	String name = DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER;
	String destination = (String) message.getHeaders().get(name);
	if (!StringUtils.hasText(destination)) {
		throw new IllegalStateException("No lookup destination header in " + message);
	}

	return (destination.startsWith("/") ?
			new String[] {defaultPrefix + destination} : new String[] {defaultPrefix + '/' + destination});
}
 
源代码25 项目: kfs   文件: DefaultListableBeanFactory.java
/**
 * Find a {@link Annotation} of <code>annotationType</code> on the specified
 * bean, traversing its interfaces and super classes if no annotation can be
 * found on the given class itself, as well as checking its raw bean class
 * if not found on the exposed bean reference (e.g. in case of a proxy).
 */
@Override
   public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
	A ann = null;
	Class beanType = getType(beanName);
	if (beanType != null) {
		ann = AnnotationUtils.findAnnotation(beanType, annotationType);
	}
	if (ann == null && containsBeanDefinition(beanName)) {
		BeanDefinition bd = getMergedBeanDefinition(beanName);
		if (bd instanceof AbstractBeanDefinition) {
			AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
			if (abd.hasBeanClass()) {
				ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType);
			}
		}
	}
	return ann;
}
 
源代码26 项目: etf-webapp   文件: WebExceptionHandler.java
private ModelAndView createError(final Exception e, final String hint, final String url, boolean submitReport)
        throws Exception {
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        // Not associated with a view
        throw e;
    }

    final ModelAndView mav = new ModelAndView();
    mav.addObject("ex", e);
    if (hint != null) {
        mav.addObject("hint", hint);
    }
    mav.addObject("url", url);
    final UUID exceptionId = UUID.randomUUID();
    mav.addObject("exid", "EXID-" + exceptionId.toString());
    logger.error(
            "EXID-" + exceptionId.toString() + ": An exception occurred while trying to access \"" +
                    url + "\"",
            e);
    mav.addObject("submitReport", submitReport && View.getSubmitAnalysisData().equals("true"));
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
}
 
源代码27 项目: springboot-plus   文件: AnnotationUtil.java
/**
 * 获取一个类注解的名称和值
 *
 * @param annotationClasss   注解定义类
 * @param useAnnotationClass 使用注解的类
 * @return List<Map<String, Object>>
 * @throws Exception
 */
public List<Map<String, Object>> getAnnotations(Class annotationClasss, Class useAnnotationClass) {
    List<Map<String, Object>> annotationMapList = new ArrayList<>();

    Field[] fields = useAnnotationClass.getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(annotationClasss)) {
            Annotation p = field.getAnnotation(annotationClasss);
            Map map = AnnotationUtils.getAnnotationAttributes(p);
            map.put("fieldName", field.getName());
            annotationMapList.add(map);
        }
    }

    return annotationMapList;
}
 
private Set<EventSourceConsumer> consumerAnnotationsOf(final Method method) {
    Set<EventSourceConsumer> listeners = new HashSet<>();
    EventSourceConsumer ann = AnnotationUtils.findAnnotation(method, EventSourceConsumer.class);
    if (ann != null) {
        listeners.add(ann);
    }
    return listeners;
}
 
源代码29 项目: lams   文件: AnnotationJmxAttributeSource.java
@Override
public org.springframework.jmx.export.metadata.ManagedOperationParameter[] getManagedOperationParameters(Method method)
		throws InvalidMetadataException {

	Set<ManagedOperationParameter> anns = AnnotationUtils.getRepeatableAnnotations(
			method, ManagedOperationParameter.class, ManagedOperationParameters.class);
	return copyPropertiesToBeanArray(anns, org.springframework.jmx.export.metadata.ManagedOperationParameter.class);
}
 
@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
	if (this.validator == null) {
		return null;
	}
	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});
			String name = Conventions.getVariableNameForParameter(parameter);
			return target -> {
				BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name);
				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);
				}
			};
		}
	}
	return null;
}
 
 类所在包
 同包方法