Java Code Examples for org.springframework.core.annotation.AnnotationAttributes#get()

The following examples show how to use org.springframework.core.annotation.AnnotationAttributes#get() . 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: AnnotationBeanNameGenerator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Derive a bean name from one of the annotations on the class.
 * @param annotatedDef the annotation-aware bean definition
 * @return the bean name, or {@code null} if none is found
 */
@Nullable
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
	AnnotationMetadata amd = annotatedDef.getMetadata();
	Set<String> types = amd.getAnnotationTypes();
	String beanName = null;
	for (String type : types) {
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
		if (attributes != null && isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
			Object value = attributes.get("value");
			if (value instanceof String) {
				String strVal = (String) value;
				if (StringUtils.hasLength(strVal)) {
					if (beanName != null && !strVal.equals(beanName)) {
						throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
								"component names: '" + beanName + "' versus '" + strVal + "'");
					}
					beanName = strVal;
				}
			}
		}
	}
	return beanName;
}
 
Example 2
Source File: SecurityImportSelector.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> doSelect(AnnotationMetadata metadata, AnnotationAttributes attributes) {
	ConfigOptions mode = (ConfigOptions)attributes.get("mode");
	List<String> classNames = new ArrayList<>();
	if(mode==ConfigOptions.URL){
		classNames.add(UrlBasedSecurityConfig.class.getName());
	}else if(mode==ConfigOptions.METHOD){
		classNames.add(MethodBasedSecurityConfig.class.getName());
	}else{
		Class<?>[] configClass = (Class<?>[])attributes.get("configClass");
		if(configClass==null || configClass.length==0){
			throw new BaseException("no security config class set!");
		}
		for(Class<?> cls : configClass){
			classNames.add(cls.getName());
		}
	}
	boolean enableJavaStylePermissionManage = (boolean)attributes.get("enableJavaStylePermissionManage");
	if(enableJavaStylePermissionManage){
		classNames.add(PermissionContextConfig.class.getName());
	}
	return classNames;
}
 
Example 3
Source File: AnnotationBeanNameGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Derive a bean name from one of the annotations on the class.
 * @param annotatedDef the annotation-aware bean definition
 * @return the bean name, or {@code null} if none is found
 */
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
	AnnotationMetadata amd = annotatedDef.getMetadata();
	Set<String> types = amd.getAnnotationTypes();
	String beanName = null;
	for (String type : types) {
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
		if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
			Object value = attributes.get("value");
			if (value instanceof String) {
				String strVal = (String) value;
				if (StringUtils.hasLength(strVal)) {
					if (beanName != null && !strVal.equals(beanName)) {
						throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
								"component names: '" + beanName + "' versus '" + strVal + "'");
					}
					beanName = strVal;
				}
			}
		}
	}
	return beanName;
}
 
Example 4
Source File: AnnotationBeanNameGenerator.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
/**
 * Derive a bean name from one of the annotations on the class.
 *
 * @param annotatedDef the annotation-aware bean definition
 * @return the bean name, or {@code null} if none is found
 */
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
    AnnotationMetadata amd = annotatedDef.getMetadata();
    Set<String> types = amd.getAnnotationTypes();
    String beanName = null;
    for (String type : types) {
        AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
        if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
            Object value = attributes.get("value");
            if (value instanceof String) {
                String strVal = (String) value;
                if (StringUtils.hasLength(strVal)) {
                    if (beanName != null && !strVal.equals(beanName)) {
                        throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
                                "component names: '" + beanName + "' versus '" + strVal + "'");
                    }
                    beanName = strVal;
                }
            }
        }
    }
    return beanName;
}
 
Example 5
Source File: AutoProxyRegistrar.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Register, escalate, and configure the standard auto proxy creator (APC) against the
 * given registry. Works by finding the nearest annotation declared on the importing
 * {@code @Configuration} class that has both {@code mode} and {@code proxyTargetClass}
 * attributes. If {@code mode} is set to {@code PROXY}, the APC is registered; if
 * {@code proxyTargetClass} is set to {@code true}, then the APC is forced to use
 * subclass (CGLIB) proxying.
 * <p>Several {@code @Enable*} annotations expose both {@code mode} and
 * {@code proxyTargetClass} attributes. It is important to note that most of these
 * capabilities end up sharing a {@linkplain AopConfigUtils#AUTO_PROXY_CREATOR_BEAN_NAME
 * single APC}. For this reason, this implementation doesn't "care" exactly which
 * annotation it finds -- as long as it exposes the right {@code mode} and
 * {@code proxyTargetClass} attributes, the APC can be registered and configured all
 * the same.
 */
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	boolean candidateFound = false;
	Set<String> annoTypes = importingClassMetadata.getAnnotationTypes();
	for (String annoType : annoTypes) {
		AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
		Object mode = candidate.get("mode");
		Object proxyTargetClass = candidate.get("proxyTargetClass");
		if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
				Boolean.class == proxyTargetClass.getClass()) {
			candidateFound = true;
			if (mode == AdviceMode.PROXY) {
				AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
				if ((Boolean) proxyTargetClass) {
					AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
					return;
				}
			}
		}
	}
	if (!candidateFound) {
		String name = getClass().getSimpleName();
		logger.warn(String.format("%s was imported but no annotations were found " +
				"having both 'mode' and 'proxyTargetClass' attributes of type " +
				"AdviceMode and boolean respectively. This means that auto proxy " +
				"creator registration and configuration may not have occured as " +
				"intended, and components may not be proxied as expected. Check to " +
				"ensure that %s has been @Import'ed on the same class where these " +
				"annotations are declared; otherwise remove the import of %s " +
				"altogether.", name, name, name));
	}
}
 
Example 6
Source File: AnnotationMetadataTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * In order to preserve backward-compatibility, {@link StandardAnnotationMetadata}
 * defaults to return nested annotations and annotation arrays as actual
 * Annotation instances. It is recommended for compatibility with ASM-based
 * AnnotationMetadata implementations to set the 'nestedAnnotationsAsMap' flag to
 * 'true' as is done in the main test above.
 */
@Test
public void standardAnnotationMetadata_nestedAnnotationsAsMap_false() throws Exception {
	AnnotationMetadata metadata = new StandardAnnotationMetadata(AnnotatedComponent.class);
	AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName());
	Annotation[] nestedAnnoArray = (Annotation[]) specialAttrs.get("nestedAnnoArray");
	assertThat(nestedAnnoArray[0], instanceOf(NestedAnno.class));
}
 
Example 7
Source File: QualifierAnnotationAutowireCandidateResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract the value attribute from the given annotation.
 * @since 4.3
 */
protected Object extractValue(AnnotationAttributes attr) {
	Object value = attr.get(AnnotationUtils.VALUE);
	if (value == null) {
		throw new IllegalStateException("Value annotation must have a value attribute");
	}
	return value;
}
 
Example 8
Source File: QualifierAnnotationAutowireCandidateResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Extract the value attribute from the given annotation.
 * @since 4.3
 */
protected Object extractValue(AnnotationAttributes attr) {
	Object value = attr.get(AnnotationUtils.VALUE);
	if (value == null) {
		throw new IllegalStateException("Value annotation must have a value attribute");
	}
	return value;
}
 
Example 9
Source File: AnnotationMetadataTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * In order to preserve backward-compatibility, {@link StandardAnnotationMetadata}
 * defaults to return nested annotations and annotation arrays as actual
 * Annotation instances. It is recommended for compatibility with ASM-based
 * AnnotationMetadata implementations to set the 'nestedAnnotationsAsMap' flag to
 * 'true' as is done in the main test above.
 */
@Test
public void standardAnnotationMetadata_nestedAnnotationsAsMap_false() throws Exception {
	AnnotationMetadata metadata = new StandardAnnotationMetadata(AnnotatedComponent.class);
	AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName());
	Annotation[] nestedAnnoArray = (Annotation[]) specialAttrs.get("nestedAnnoArray");
	assertThat(nestedAnnoArray[0], instanceOf(NestedAnno.class));
}
 
Example 10
Source File: AutoProxyRegistrar.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Register, escalate, and configure the standard auto proxy creator (APC) against the
 * given registry. Works by finding the nearest annotation declared on the importing
 * {@code @Configuration} class that has both {@code mode} and {@code proxyTargetClass}
 * attributes. If {@code mode} is set to {@code PROXY}, the APC is registered; if
 * {@code proxyTargetClass} is set to {@code true}, then the APC is forced to use
 * subclass (CGLIB) proxying.
 * <p>Several {@code @Enable*} annotations expose both {@code mode} and
 * {@code proxyTargetClass} attributes. It is important to note that most of these
 * capabilities end up sharing a {@linkplain AopConfigUtils#AUTO_PROXY_CREATOR_BEAN_NAME
 * single APC}. For this reason, this implementation doesn't "care" exactly which
 * annotation it finds -- as long as it exposes the right {@code mode} and
 * {@code proxyTargetClass} attributes, the APC can be registered and configured all
 * the same.
 */
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	boolean candidateFound = false;
	Set<String> annoTypes = importingClassMetadata.getAnnotationTypes();
	for (String annoType : annoTypes) {
		AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
		if (candidate == null) {
			continue;
		}
		Object mode = candidate.get("mode");
		Object proxyTargetClass = candidate.get("proxyTargetClass");
		if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
				Boolean.class == proxyTargetClass.getClass()) {
			candidateFound = true;
			if (mode == AdviceMode.PROXY) {
				AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
				if ((Boolean) proxyTargetClass) {
					AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
					return;
				}
			}
		}
	}
	if (!candidateFound && logger.isInfoEnabled()) {
		String name = getClass().getSimpleName();
		logger.info(String.format("%s was imported but no annotations were found " +
				"having both 'mode' and 'proxyTargetClass' attributes of type " +
				"AdviceMode and boolean respectively. This means that auto proxy " +
				"creator registration and configuration may not have occurred as " +
				"intended, and components may not be proxied as expected. Check to " +
				"ensure that %s has been @Import'ed on the same class where these " +
				"annotations are declared; otherwise remove the import of %s " +
				"altogether.", name, name, name));
	}
}
 
Example 11
Source File: QualifierAnnotationAutowireCandidateResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Extract the value attribute from the given annotation.
 * @since 4.3
 */
protected Object extractValue(AnnotationAttributes attr) {
	Object value = attr.get(AnnotationUtils.VALUE);
	if (value == null) {
		throw new IllegalStateException("Value annotation must have a value attribute");
	}
	return value;
}
 
Example 12
Source File: AnnotationMetadataTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * In order to preserve backward-compatibility, {@link StandardAnnotationMetadata}
 * defaults to return nested annotations and annotation arrays as actual
 * Annotation instances. It is recommended for compatibility with ASM-based
 * AnnotationMetadata implementations to set the 'nestedAnnotationsAsMap' flag to
 * 'true' as is done in the main test above.
 */
@Test
@Deprecated
public void standardAnnotationMetadata_nestedAnnotationsAsMap_false() {
	AnnotationMetadata metadata = new StandardAnnotationMetadata(AnnotatedComponent.class);
	AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName());
	Annotation[] nestedAnnoArray = (Annotation[]) specialAttrs.get("nestedAnnoArray");
	assertThat(nestedAnnoArray[0], instanceOf(NestedAnno.class));
}
 
Example 13
Source File: AutoProxyRegistrar.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Register, escalate, and configure the standard auto proxy creator (APC) against the
 * given registry. Works by finding the nearest annotation declared on the importing
 * {@code @Configuration} class that has both {@code mode} and {@code proxyTargetClass}
 * attributes. If {@code mode} is set to {@code PROXY}, the APC is registered; if
 * {@code proxyTargetClass} is set to {@code true}, then the APC is forced to use
 * subclass (CGLIB) proxying.
 * <p>Several {@code @Enable*} annotations expose both {@code mode} and
 * {@code proxyTargetClass} attributes. It is important to note that most of these
 * capabilities end up sharing a {@linkplain AopConfigUtils#AUTO_PROXY_CREATOR_BEAN_NAME
 * single APC}. For this reason, this implementation doesn't "care" exactly which
 * annotation it finds -- as long as it exposes the right {@code mode} and
 * {@code proxyTargetClass} attributes, the APC can be registered and configured all
 * the same.
 */
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	boolean candidateFound = false;
	Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
	for (String annType : annTypes) {
		AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
		if (candidate == null) {
			continue;
		}
		Object mode = candidate.get("mode");
		Object proxyTargetClass = candidate.get("proxyTargetClass");
		if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
				Boolean.class == proxyTargetClass.getClass()) {
			candidateFound = true;
			if (mode == AdviceMode.PROXY) {
				AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
				if ((Boolean) proxyTargetClass) {
					AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
					return;
				}
			}
		}
	}
	if (!candidateFound && logger.isInfoEnabled()) {
		String name = getClass().getSimpleName();
		logger.info(String.format("%s was imported but no annotations were found " +
				"having both 'mode' and 'proxyTargetClass' attributes of type " +
				"AdviceMode and boolean respectively. This means that auto proxy " +
				"creator registration and configuration may not have occurred as " +
				"intended, and components may not be proxied as expected. Check to " +
				"ensure that %s has been @Import'ed on the same class where these " +
				"annotations are declared; otherwise remove the import of %s " +
				"altogether.", name, name, name));
	}
}
 
Example 14
Source File: AnnotationReadingVisitorUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Retrieve the merged attributes of the annotation of the given type,
 * if any, from the supplied {@code attributesMap}.
 * <p>Annotation attribute values appearing <em>lower</em> in the annotation
 * hierarchy (i.e., closer to the declaring class) will override those
 * defined <em>higher</em> in the annotation hierarchy.
 * @param attributesMap the map of annotation attribute lists, keyed by
 * annotation type name
 * @param metaAnnotationMap the map of meta annotation relationships,
 * keyed by annotation type name
 * @param annotationName the fully qualified class name of the annotation
 * type to look for
 * @return the merged annotation attributes, or {@code null} if no
 * matching annotation is present in the {@code attributesMap}
 * @since 4.0.3
 */
@Nullable
public static AnnotationAttributes getMergedAnnotationAttributes(
		LinkedMultiValueMap<String, AnnotationAttributes> attributesMap,
		Map<String, Set<String>> metaAnnotationMap, String annotationName) {

	// Get the unmerged list of attributes for the target annotation.
	List<AnnotationAttributes> attributesList = attributesMap.get(annotationName);
	if (CollectionUtils.isEmpty(attributesList)) {
		return null;
	}

	// To start with, we populate the result with a copy of all attribute values
	// from the target annotation. A copy is necessary so that we do not
	// inadvertently mutate the state of the metadata passed to this method.
	AnnotationAttributes result = new AnnotationAttributes(attributesList.get(0));

	Set<String> overridableAttributeNames = new HashSet<>(result.keySet());
	overridableAttributeNames.remove(AnnotationUtils.VALUE);

	// Since the map is a LinkedMultiValueMap, we depend on the ordering of
	// elements in the map and reverse the order of the keys in order to traverse
	// "down" the annotation hierarchy.
	List<String> annotationTypes = new ArrayList<>(attributesMap.keySet());
	Collections.reverse(annotationTypes);

	// No need to revisit the target annotation type:
	annotationTypes.remove(annotationName);

	for (String currentAnnotationType : annotationTypes) {
		List<AnnotationAttributes> currentAttributesList = attributesMap.get(currentAnnotationType);
		if (!ObjectUtils.isEmpty(currentAttributesList)) {
			Set<String> metaAnns = metaAnnotationMap.get(currentAnnotationType);
			if (metaAnns != null && metaAnns.contains(annotationName)) {
				AnnotationAttributes currentAttributes = currentAttributesList.get(0);
				for (String overridableAttributeName : overridableAttributeNames) {
					Object value = currentAttributes.get(overridableAttributeName);
					if (value != null) {
						// Store the value, potentially overriding a value from an attribute
						// of the same name found higher in the annotation hierarchy.
						result.put(overridableAttributeName, value);
					}
				}
			}
		}
	}

	return result;
}
 
Example 15
Source File: AnnotationReadingVisitorUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve the merged attributes of the annotation of the given type,
 * if any, from the supplied {@code attributesMap}.
 * <p>Annotation attribute values appearing <em>lower</em> in the annotation
 * hierarchy (i.e., closer to the declaring class) will override those
 * defined <em>higher</em> in the annotation hierarchy.
 * @param attributesMap the map of annotation attribute lists, keyed by
 * annotation type name
 * @param metaAnnotationMap the map of meta annotation relationships,
 * keyed by annotation type name
 * @param annotationName the fully qualified class name of the annotation
 * type to look for
 * @return the merged annotation attributes, or {@code null} if no
 * matching annotation is present in the {@code attributesMap}
 * @since 4.0.3
 */
public static AnnotationAttributes getMergedAnnotationAttributes(
		LinkedMultiValueMap<String, AnnotationAttributes> attributesMap,
		Map<String, Set<String>> metaAnnotationMap, String annotationName) {

	// Get the unmerged list of attributes for the target annotation.
	List<AnnotationAttributes> attributesList = attributesMap.get(annotationName);
	if (attributesList == null || attributesList.isEmpty()) {
		return null;
	}

	// To start with, we populate the results with a copy of all attribute
	// values from the target annotation. A copy is necessary so that we do
	// not inadvertently mutate the state of the metadata passed to this
	// method.
	AnnotationAttributes results = new AnnotationAttributes(attributesList.get(0));

	Set<String> overridableAttributeNames = new HashSet<String>(results.keySet());
	overridableAttributeNames.remove(AnnotationUtils.VALUE);

	// Since the map is a LinkedMultiValueMap, we depend on the ordering of
	// elements in the map and reverse the order of the keys in order to traverse
	// "down" the annotation hierarchy.
	List<String> annotationTypes = new ArrayList<String>(attributesMap.keySet());
	Collections.reverse(annotationTypes);

	// No need to revisit the target annotation type:
	annotationTypes.remove(annotationName);

	for (String currentAnnotationType : annotationTypes) {
		List<AnnotationAttributes> currentAttributesList = attributesMap.get(currentAnnotationType);
		if (!ObjectUtils.isEmpty(currentAttributesList)) {
			Set<String> metaAnns = metaAnnotationMap.get(currentAnnotationType);
			if (metaAnns != null && metaAnns.contains(annotationName)) {
				AnnotationAttributes currentAttributes = currentAttributesList.get(0);
				for (String overridableAttributeName : overridableAttributeNames) {
					Object value = currentAttributes.get(overridableAttributeName);
					if (value != null) {
						// Store the value, potentially overriding a value from an
						// attribute of the same name found higher in the annotation
						// hierarchy.
						results.put(overridableAttributeName, value);
					}
				}
			}
		}
	}

	return results;
}
 
Example 16
Source File: HttpdocFilterRegistrar.java    From httpdoc with Apache License 2.0 4 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableHttpdoc.class.getName()));
    BeanDefinition httpdoc = new RootBeanDefinition(FilterRegistrationBean.class);

    String name = attributes.getString("name");
    httpdoc.getPropertyValues().add("name", name);

    boolean asyncSupported = attributes.getBoolean("asyncSupported");
    httpdoc.getPropertyValues().add("asyncSupported", asyncSupported);

    DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes.get("dispatcherTypes");
    httpdoc.getPropertyValues().add("dispatcherTypes", EnumSet.of(dispatcherTypes[0], dispatcherTypes));

    boolean matchAfter = attributes.getBoolean("matchAfter");
    httpdoc.getPropertyValues().add("matchAfter", matchAfter);

    boolean enabled = attributes.getBoolean("enabled");
    httpdoc.getPropertyValues().add("enabled", enabled);

    int order = attributes.getNumber("order");
    httpdoc.getPropertyValues().add("order", order);

    String[] patterns = attributes.getStringArray("value");
    httpdoc.getPropertyValues().add("urlPatterns", Arrays.asList(patterns));

    Class<?> filter = attributes.getClass("filter");
    httpdoc.getPropertyValues().add("filter", newInstance(filter));

    Map<String, String> parameters = new LinkedHashMap<>();
    AnnotationAttributes[] params = attributes.getAnnotationArray("params");
    for (AnnotationAttributes param : params) parameters.put(param.getString("name"), param.getString("value"));

    parameters.put("packages", concat(attributes.getStringArray("packages")));
    parameters.put("httpdoc", attributes.getString("httpdoc"));
    parameters.put("protocol", attributes.getString("protocol"));
    parameters.put("hostname", attributes.getString("hostname"));
    parameters.put("port", attributes.getNumber("port").toString());
    parameters.put("context", attributes.getString("context"));
    parameters.put("version", attributes.getString("version"));
    parameters.put("dateFormat", attributes.getString("dateFormat"));
    parameters.put("description", attributes.getString("description"));
    parameters.put("charset", attributes.getString("charset"));
    parameters.put("contentType", attributes.getString("contentType"));
    parameters.put("translator", attributes.getClass("translator").getName());
    parameters.put("supplier", attributes.getClass("supplier").getName());
    parameters.put("interpreter", attributes.getClass("interpreter").getName());
    parameters.put("converter", attributes.getClass("converter").getName());
    parameters.put("serializer", attributes.getClass("serializer").getName());
    parameters.put("conversionProvider", attributes.getClass("conversionProvider").getName());

    httpdoc.getPropertyValues().add("initParameters", parameters);

    String beanName = attributes.getString("bean");
    registry.registerBeanDefinition(beanName, httpdoc);
}
 
Example 17
Source File: BladeFeignClientsRegistrar.java    From blade-tool with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
	List<String> feignClients = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
	// 如果 spring.factories 里为空
	if (feignClients.isEmpty()) {
		return;
	}
	for (String className : feignClients) {
		try {
			Class<?> clazz = beanClassLoader.loadClass(className);
			AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(clazz, FeignClient.class);
			if (attributes == null) {
				continue;
			}
			// 如果已经存在该 bean,支持原生的 Feign
			if (registry.containsBeanDefinition(className)) {
				continue;
			}
			registerClientConfiguration(registry, getClientName(attributes), attributes.get("configuration"));

			validate(attributes);
			BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
			definition.addPropertyValue("url", getUrl(attributes));
			definition.addPropertyValue("path", getPath(attributes));
			String name = getName(attributes);
			definition.addPropertyValue("name", name);

			// 兼容最新版本的 spring-cloud-openfeign,尚未发布
			StringBuilder aliasBuilder = new StringBuilder(18);
			if (attributes.containsKey("contextId")) {
				String contextId = getContextId(attributes);
				aliasBuilder.append(contextId);
				definition.addPropertyValue("contextId", contextId);
			} else {
				aliasBuilder.append(name);
			}

			definition.addPropertyValue("type", className);
			definition.addPropertyValue("decode404", attributes.get("decode404"));
			definition.addPropertyValue("fallback", attributes.get("fallback"));
			definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
			definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

			AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();

			// alias
			String alias = aliasBuilder.append("FeignClient").toString();

			// has a default, won't be null
			boolean primary = (Boolean)attributes.get("primary");

			beanDefinition.setPrimary(primary);

			String qualifier = getQualifier(attributes);
			if (StringUtils.hasText(qualifier)) {
				alias = qualifier;
			}

			BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[] { alias });
			BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
 
Example 18
Source File: AnnotationReadingVisitorUtils.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Retrieve the merged attributes of the annotation of the given type,
 * if any, from the supplied {@code attributesMap}.
 * <p>Annotation attribute values appearing <em>lower</em> in the annotation
 * hierarchy (i.e., closer to the declaring class) will override those
 * defined <em>higher</em> in the annotation hierarchy.
 * @param attributesMap the map of annotation attribute lists, keyed by
 * annotation type name
 * @param metaAnnotationMap the map of meta annotation relationships,
 * keyed by annotation type name
 * @param annotationName the fully qualified class name of the annotation
 * type to look for
 * @return the merged annotation attributes, or {@code null} if no
 * matching annotation is present in the {@code attributesMap}
 * @since 4.0.3
 */
@Nullable
public static AnnotationAttributes getMergedAnnotationAttributes(
		LinkedMultiValueMap<String, AnnotationAttributes> attributesMap,
		Map<String, Set<String>> metaAnnotationMap, String annotationName) {

	// Get the unmerged list of attributes for the target annotation.
	List<AnnotationAttributes> attributesList = attributesMap.get(annotationName);
	if (CollectionUtils.isEmpty(attributesList)) {
		return null;
	}

	// To start with, we populate the result with a copy of all attribute values
	// from the target annotation. A copy is necessary so that we do not
	// inadvertently mutate the state of the metadata passed to this method.
	AnnotationAttributes result = new AnnotationAttributes(attributesList.get(0));

	Set<String> overridableAttributeNames = new HashSet<>(result.keySet());
	overridableAttributeNames.remove(AnnotationUtils.VALUE);

	// Since the map is a LinkedMultiValueMap, we depend on the ordering of
	// elements in the map and reverse the order of the keys in order to traverse
	// "down" the annotation hierarchy.
	List<String> annotationTypes = new ArrayList<>(attributesMap.keySet());
	Collections.reverse(annotationTypes);

	// No need to revisit the target annotation type:
	annotationTypes.remove(annotationName);

	for (String currentAnnotationType : annotationTypes) {
		List<AnnotationAttributes> currentAttributesList = attributesMap.get(currentAnnotationType);
		if (!ObjectUtils.isEmpty(currentAttributesList)) {
			Set<String> metaAnns = metaAnnotationMap.get(currentAnnotationType);
			if (metaAnns != null && metaAnns.contains(annotationName)) {
				AnnotationAttributes currentAttributes = currentAttributesList.get(0);
				for (String overridableAttributeName : overridableAttributeNames) {
					Object value = currentAttributes.get(overridableAttributeName);
					if (value != null) {
						// Store the value, potentially overriding a value from an attribute
						// of the same name found higher in the annotation hierarchy.
						result.put(overridableAttributeName, value);
					}
				}
			}
		}
	}

	return result;
}
 
Example 19
Source File: EnableJFishBootExtensionSelector.java    From onetwo with Apache License 2.0 4 votes vote down vote up
@Override
protected List<String> doSelect(AnnotationMetadata metadata, AnnotationAttributes attributes) {
	List<String> classNames = new ArrayList<String>();

	//store 在BootCommonServiceConfig之前初始化,因为BootCommonService依赖filestore来加载
	classNames.add(OssConfiguration.class.getName());
	classNames.add(CosConfiguration.class.getName());
	
	if(attributes.getBoolean("enableCommonService")){
		classNames.add(BootCommonServiceConfig.class.getName());
	}
	
	classNames.add(BootFixedConfiguration.class.getName());
	AppcationType appcationType = (AppcationType)attributes.get("appcationType");
	if(appcationType==AppcationType.WEB_SERVICE){
		classNames.add(BootMSContextAutoConfig.class.getName());
	}else if(appcationType==AppcationType.WEB_UI){
		classNames.add(BootWebUIContextAutoConfig.class.getName());
	}
	
	classNames.add(ExcelViewConfiguration.class.getName());
	classNames.add(CorsFilterConfiguration.class.getName());
	
	classNames.add(BootDbmConfiguration.class.getName());
	classNames.add(ErrorHandleConfiguration.class.getName());
	classNames.add(EnhanceRequestMappingConfiguration.class.getName());

	classNames.add(JwtContextConfig.class.getName());
	
	classNames.add(OAuth2SsoClientAutoContextConfig.class.getName());
	classNames.add(RedisConfiguration.class.getName());
	classNames.add(AsyncMvcConfiguration.class.getName());
	classNames.add(AsyncTaskConfiguration.class.getName());
	classNames.add(AccessLogConfiguration.class.getName());
	classNames.add(GraceKillConfiguration.class.getName());

	//cache
	classNames.add(SpringCacheConfiguration.class.getName());
	classNames.add(RedissonConfiguration.class.getName());
	
	
	//swagger
	classNames.add(SwaggerConfiguration.class.getName());
	
	//activemq
	classNames.add("org.onetwo.boot.module.activemq.ActivemqConfiguration");
	
	//session
	classNames.add(BootSpringSessionConfiguration.class.getName());
	
	Collection<String> exts = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(this.annotationClass, this.beanClassLoader));
	for(String extClassName : exts){
		Class<?> extClass;
		try {
			extClass = ClassUtils.forName(extClassName, beanClassLoader);
		} catch (ClassNotFoundException | LinkageError e) {
			throw new BaseException("load "+this.annotationClass.getSimpleName()+" error. extension class: " + extClassName, e);
		}
		if(extClass.getAnnotation(JFishWebPlugin.class)==null){
			throw new BaseException("extension class["+extClassName+"] must be annotated by "+JFishWebPlugin.class.getName());
		}
		classNames.add(extClassName);
	}
	
	
	return classNames;
}
 
Example 20
Source File: HttpdocFilterRegistrar.java    From halo-docs with Apache License 2.0 4 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableDoc.class.getName()));


    BeanDefinition httpdoc = new RootBeanDefinition(FilterRegistrationBean.class);

    String name = attributes.getString("name");
    httpdoc.getPropertyValues().add("name", name);

    boolean asyncSupported = attributes.getBoolean("asyncSupported");
    httpdoc.getPropertyValues().add("asyncSupported", asyncSupported);

    DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes.get("dispatcherTypes");
    httpdoc.getPropertyValues().add("dispatcherTypes", EnumSet.of(dispatcherTypes[0], dispatcherTypes));

    boolean matchAfter = attributes.getBoolean("matchAfter");
    httpdoc.getPropertyValues().add("matchAfter", matchAfter);

    boolean enabled = attributes.getBoolean("enabled");
    httpdoc.getPropertyValues().add("enabled", enabled);

    int order = attributes.getNumber("order");
    httpdoc.getPropertyValues().add("order", order);

    String[] patterns = attributes.getStringArray("value");
    httpdoc.getPropertyValues().add("urlPatterns", Arrays.asList(patterns));

    Class<?> filter = attributes.getClass("filter");
    httpdoc.getPropertyValues().add("filter", newInstance(filter));

    Map<String, String> parameters = new LinkedHashMap<>();
    AnnotationAttributes[] params = attributes.getAnnotationArray("params");
    for (AnnotationAttributes param : params) parameters.put(param.getString("name"), param.getString("value"));

    parameters.put("packages", concat(attributes.getStringArray("packages")));
    parameters.put("httpdoc", attributes.getString("httpdoc"));
    parameters.put("protocol", attributes.getString("protocol"));
    parameters.put("hostname", attributes.getString("hostname"));
    parameters.put("port", attributes.getNumber("port").toString());
    parameters.put("context", attributes.getString("context"));
    parameters.put("version", attributes.getString("version"));
    parameters.put("dateFormat", attributes.getString("dateFormat"));
    parameters.put("description", attributes.getString("description"));
    parameters.put("charset", attributes.getString("charset"));
    parameters.put("contentType", attributes.getString("contentType"));
    parameters.put("translator", attributes.getClass("translator").getName());
    parameters.put("supplier", attributes.getClass("supplier").getName());
    parameters.put("interpreter", attributes.getClass("interpreter").getName());
    parameters.put("converter", attributes.getClass("converter").getName());
    parameters.put("serializer", attributes.getClass("serializer").getName());
    parameters.put("conversionProvider", attributes.getClass("conversionProvider").getName());

    httpdoc.getPropertyValues().add("initParameters", parameters);

    String beanName = attributes.getString("bean");
    registry.registerBeanDefinition(beanName, httpdoc);
}