List of usage examples for org.springframework.core.annotation AnnotationUtils findAnnotation
@Nullable public static <A extends Annotation> A findAnnotation(Class<?> clazz, @Nullable Class<A> annotationType)
From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java
private boolean supportsInternal(Class<?> clazz, boolean checkForXmlRootElement) { if (checkForXmlRootElement && AnnotationUtils.findAnnotation(clazz, XmlRootElement.class) == null) { return false; }/* www.jav a2 s .co m*/ if (StringUtils.hasLength(this.contextPath)) { String packageName = ClassUtils.getPackageName(clazz); String[] contextPaths = StringUtils.tokenizeToStringArray(this.contextPath, ":"); for (String contextPath : contextPaths) { if (contextPath.equals(packageName)) { return true; } } return false; } else if (!ObjectUtils.isEmpty(this.classesToBeBound)) { return Arrays.asList(this.classesToBeBound).contains(clazz); } return false; }
From source file:org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.java
private AnnotationAttributes enableMethodSecurity() { if (enableMethodSecurity == null) { // if it is null look at this instance (i.e. a subclass was used) EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(), EnableGlobalMethodSecurity.class); Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required"); Map<String, Object> methodSecurityAttrs = AnnotationUtils .getAnnotationAttributes(methodSecurityAnnotation); this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs); }//from www . j a v a 2s .c om return this.enableMethodSecurity; }
From source file:org.springframework.statemachine.processor.StateMachineAnnotationPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { Assert.notNull(beanFactory, "BeanFactory must not be null"); final Class<?> beanClass = getBeanClass(bean); if (AnnotationUtils.findAnnotation(beanClass, WithStateMachine.class) == null) { // we only post-process beans having WithStateMachine // in it or as a meta annotation return bean; }/* w w w.j a v a2 s .c o m*/ ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { @SuppressWarnings({ "unchecked", "rawtypes" }) public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { for (Class<? extends Annotation> ppa : postProcessors.keySet()) { Annotation metaAnnotation = AnnotationUtils.findAnnotation(method, ppa); if (metaAnnotation == null) { continue; } for (Annotation a : AnnotationUtils.getAnnotations(method)) { MethodAnnotationPostProcessor postProcessor = metaAnnotation != null ? postProcessors.get(metaAnnotation.annotationType()) : null; if (postProcessor != null && shouldCreateHandler(a)) { Object result = postProcessor.postProcess(beanClass, bean, beanName, method, metaAnnotation, a); if (result != null && result instanceof StateMachineHandler) { String endpointBeanName = generateBeanName(beanName, method, a.annotationType()); if (result instanceof BeanNameAware) { ((BeanNameAware) result).setBeanName(endpointBeanName); } beanFactory.registerSingleton(endpointBeanName, result); if (result instanceof BeanFactoryAware) { ((BeanFactoryAware) result).setBeanFactory(beanFactory); } if (result instanceof InitializingBean) { try { ((InitializingBean) result).afterPropertiesSet(); } catch (Exception e) { throw new BeanInitializationException( "failed to initialize annotated component", e); } } if (result instanceof Lifecycle) { lifecycles.add((Lifecycle) result); if (result instanceof SmartLifecycle && ((SmartLifecycle) result).isAutoStartup()) { ((SmartLifecycle) result).start(); } } if (result instanceof ApplicationListener) { listeners.add((ApplicationListener) result); } } } } } } }); return bean; }
From source file:org.springframework.statemachine.processor.StateMachineHandlerCallHelper.java
@SuppressWarnings("unchecked") @Override/*from w ww . j a va 2 s . c o m*/ public void afterPropertiesSet() throws Exception { if (!(beanFactory instanceof ListableBeanFactory)) { log.info("Beanfactory is not instance of ListableBeanFactory, was " + beanFactory + " thus Disabling handlers."); return; } if (beanFactory.containsBean(StateMachineHandlerApplicationListener.BEAN_NAME)) { this.stateMachineHandlerApplicationListener = beanFactory.getBean( StateMachineHandlerApplicationListener.BEAN_NAME, StateMachineHandlerApplicationListener.class); } for (StateMachineHandler<? extends Annotation, S, E> handler : beanFactory .getBeansOfType(StateMachineHandler.class).values()) { Annotation annotation = handler.getAnnotation(); Annotation metaAnnotation = handler.getMetaAnnotation(); WithStateMachine withStateMachine = AnnotationUtils.findAnnotation(handler.getBeanClass(), WithStateMachine.class); String statemachineBeanName = withStateMachine.name(); String key = metaAnnotation.annotationType().getName() + statemachineBeanName; List<CacheEntry> list = cache.get(key); if (list == null) { list = new ArrayList<>(); cache.put(key, list); } list.add(new CacheEntry(handler, annotation, metaAnnotation)); } }
From source file:org.springframework.statemachine.processor.StateMachineMethodInvokerHelper.java
private Map<String, Map<Class<?>, HandlerMethod>> findHandlerMethodsForTarget(final Object targetObject, final Class<? extends Annotation> annotationType, final String methodName, final boolean requiresReply) { Map<String, Map<Class<?>, HandlerMethod>> handlerMethods = new HashMap<String, Map<Class<?>, HandlerMethod>>(); final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>(); final Map<Class<?>, HandlerMethod> candidateMessageMethods = new HashMap<Class<?>, HandlerMethod>(); final Class<?> targetClass = this.getTargetClass(targetObject); MethodFilter methodFilter = new UniqueMethodFilter(targetClass); ReflectionUtils.doWithMethods(targetClass, new MethodCallback() { @Override//from w ww.j a v a 2 s. c o m public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { boolean matchesAnnotation = false; if (method.isBridge()) { return; } if (isMethodDefinedOnObjectClass(method)) { return; } if (method.getDeclaringClass().equals(Proxy.class)) { return; } if (!Modifier.isPublic(method.getModifiers())) { return; } if (requiresReply && void.class.equals(method.getReturnType())) { return; } if (methodName != null && !methodName.equals(method.getName())) { return; } if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) { matchesAnnotation = true; } HandlerMethod handlerMethod = null; try { handlerMethod = new HandlerMethod(method); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Method [" + method + "] is not eligible for container handling.", e); } return; } Class<?> targetParameterType = handlerMethod.getTargetParameterType(); if (matchesAnnotation || annotationType == null) { if (handlerMethod.isMessageMethod()) { if (candidateMessageMethods.containsKey(targetParameterType)) { throw new IllegalArgumentException("Found more than one method match for type " + "[Message<" + targetParameterType + ">]"); } candidateMessageMethods.put(targetParameterType, handlerMethod); } else { if (candidateMethods.containsKey(targetParameterType)) { String exceptionMessage = "Found more than one method match for "; if (Void.class.equals(targetParameterType)) { exceptionMessage += "empty parameter for 'payload'"; } else { exceptionMessage += "type [" + targetParameterType + "]"; } throw new IllegalArgumentException(exceptionMessage); } candidateMethods.put(targetParameterType, handlerMethod); } } } }, methodFilter); if (!candidateMethods.isEmpty() || !candidateMessageMethods.isEmpty()) { handlerMethods.put(CANDIDATE_METHODS, candidateMethods); handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods); return handlerMethods; } Assert.state(!handlerMethods.isEmpty(), "Target object of type [" + this.targetObject.getClass() + "] has no eligible methods for handling Container."); return handlerMethods; }
From source file:org.springframework.test.context.support.AbstractTestContextBootstrapper.java
/** * {@inheritDoc}//from ww w. j av a 2 s . c om */ @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); } }
From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java
public final Object invokeHandlerMethod(Method handlerMethod, Object handler, NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod); try {/*w w w . j av a2 s . com*/ boolean debug = logger.isDebugEnabled(); for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName); if (attrValue != null) { implicitModel.addAttribute(attrName, attrValue); } } for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) { Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod); Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking model attribute method: " + attributeMethodToInvoke); } String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value(); if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) { continue; } ReflectionUtils.makeAccessible(attributeMethodToInvoke); Object attrValue = attributeMethodToInvoke.invoke(handler, args); if ("".equals(attrName)) { Class<?> resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass()); attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType, attrValue); } if (!implicitModel.containsAttribute(attrName)) { implicitModel.addAttribute(attrName, attrValue); } } Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking request handler method: " + handlerMethodToInvoke); } ReflectionUtils.makeAccessible(handlerMethodToInvoke); return handlerMethodToInvoke.invoke(handler, args); } catch (IllegalStateException ex) { // Internal assertion failed (e.g. invalid signature): // throw exception with full handler method context... throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex); } catch (InvocationTargetException ex) { // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception... ReflectionUtils.rethrowException(ex.getTargetException()); return null; } }
From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java
protected final void addReturnValueAsModelAttribute(Method handlerMethod, Class<?> handlerType, Object returnValue, ExtendedModelMap implicitModel) { ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class); String attrName = (attr != null ? attr.value() : ""); if ("".equals(attrName)) { Class<?> resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType); attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue); }/*from w w w. j ava 2s . c om*/ implicitModel.addAttribute(attrName, returnValue); }
From source file:org.springframework.web.method.ControllerAdviceBean.java
/** * Create an instance using the given bean name. * @param beanName the name of the bean//www . j a v a2 s . c o m * @param beanFactory a BeanFactory that can be used later to resolve the bean */ public ControllerAdviceBean(String beanName, BeanFactory beanFactory) { Assert.hasText(beanName, "Bean name must not be null"); Assert.notNull(beanFactory, "BeanFactory must not be null"); if (!beanFactory.containsBean(beanName)) { throw new IllegalArgumentException( "BeanFactory [" + beanFactory + "] does not contain bean with name '" + beanName + "'"); } this.bean = beanName; this.beanFactory = beanFactory; Class<?> beanType = this.beanFactory.getType(beanName); this.order = initOrderFromBeanType(beanType); ControllerAdvice annotation = AnnotationUtils.findAnnotation(beanType, ControllerAdvice.class); Assert.notNull(annotation, "BeanType [" + beanType.getName() + "] is not annotated @ControllerAdvice"); this.basePackages.addAll(initBasePackagesFromBeanType(beanType, annotation)); this.annotations.addAll(Arrays.asList(annotation.annotations())); this.assignableTypes.addAll(Arrays.asList(annotation.assignableTypes())); }
From source file:org.springframework.web.method.ControllerAdviceBean.java
/** * Create an instance using the given bean instance. * @param bean the bean//from w w w.ja va2 s. c o m */ public ControllerAdviceBean(Object bean) { Assert.notNull(bean, "Bean must not be null"); this.bean = bean; this.order = initOrderFromBean(bean); Class<?> beanType = bean.getClass(); ControllerAdvice annotation = AnnotationUtils.findAnnotation(beanType, ControllerAdvice.class); Assert.notNull(annotation, "Bean type [" + beanType.getName() + "] is not annotated @ControllerAdvice"); this.basePackages.addAll(initBasePackagesFromBeanType(beanType, annotation)); this.annotations.addAll(Arrays.asList(annotation.annotations())); this.assignableTypes.addAll(Arrays.asList(annotation.assignableTypes())); this.beanFactory = null; }