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

The following examples show how to use org.springframework.core.annotation.AnnotationAttributes#getClass() . 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: MessageLogReceiverEndpointBeanRegistrar.java    From synapse with Apache License 2.0 6 votes vote down vote up
@Override
protected void registerBeanDefinitions(final String channelName,
                                       final String beanName,
                                       final AnnotationAttributes annotationAttributes,
                                       final BeanDefinitionRegistry registry) {
    final String processorBeanName = beanName + "Processor";

    final Class<? extends MessageLog> channelSelector = annotationAttributes.getClass("selector");

    if (!registry.containsBeanDefinition(beanName)) {
        registerMessageLogReceiverEndpointBeanDefinition(registry, beanName, channelName, channelSelector);
    } else {
        throw new BeanCreationException(beanName, format("MessageLogReceiverEndpoint %s is already registered.", beanName));
    }
    if (!registry.containsBeanDefinition(processorBeanName)) {
        registerMessageLogReceiverEndpointProcessorBeanDefinition(registry, processorBeanName, beanName, channelName);
    } else {
        throw new BeanCreationException(beanName, format("MessageLogReceiverEndpointProcessor %s is already registered.", processorBeanName));
    }
}
 
Example 2
Source File: ConfigurationTypeRegistrar.java    From conf4j with MIT License 6 votes vote down vote up
private void registerConfigurationType(BeanDefinitionRegistry registry, AnnotationAttributes attributes) {
    Class<?> configurationType = attributes.getClass("value");
    String[] names = attributes.getStringArray("name");

    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(configurationType);
    addConf4jConfigurationIndicator(builder.getRawBeanDefinition(), ConfigurationIndicator.MANUAL);

    String beanName;
    String[] aliases = null;
    if (names.length == 0) {
        beanName = configurationType.getName();
    } else if (names.length == 1) {
        beanName = names[0];
    } else {
        beanName = names[0];
        aliases = ArrayUtils.subarray(names, 1, names.length);
    }

    registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
    if (aliases != null) {
        for (String alias : aliases) {
            registry.registerAlias(beanName, alias);
        }
    }
}
 
Example 3
Source File: KeyValueRepositoryConfigurationExtension.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * Detects the query creator type to be used for the factory to set. Will lookup a {@link QueryCreatorType} annotation
 * on the {@code @Enable}-annotation or use {@link SpelQueryCreator} if not found.
 *
 * @param config must not be {@literal null}.
 * @return
 */
private static Class<?> getQueryCreatorType(AnnotationRepositoryConfigurationSource config) {

	AnnotationMetadata metadata = config.getEnableAnnotationMetadata();

	Map<String, Object> queryCreatorAnnotationAttributes = metadata
			.getAnnotationAttributes(QueryCreatorType.class.getName());

	if (CollectionUtils.isEmpty(queryCreatorAnnotationAttributes)) {
		return SpelQueryCreator.class;
	}

	AnnotationAttributes queryCreatorAttributes = new AnnotationAttributes(queryCreatorAnnotationAttributes);
	return queryCreatorAttributes.getClass("value");
}
 
Example 4
Source File: MvcInterceptorManager.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected MvcInterceptorMeta asMvcInterceptorMeta(AnnotationAttributes attr){
	List<PropertyAnnoMeta> properties = propertyAnnotationReader.readProperties(attr);
	return new MvcInterceptorMeta((Class<? extends MvcInterceptor>)attr.getClass("value"), 
									attr.getBoolean("alwaysCreate"), 
									properties);
}
 
Example 5
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
	String name = propertySource.getString("name");
	if (!StringUtils.hasLength(name)) {
		name = null;
	}
	String encoding = propertySource.getString("encoding");
	if (!StringUtils.hasLength(encoding)) {
		encoding = null;
	}
	String[] locations = propertySource.getStringArray("value");
	Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
	boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

	Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
	PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
			DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

	for (String location : locations) {
		try {
			String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
			Resource resource = this.resourceLoader.getResource(resolvedLocation);
			addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
		}
		catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
			// Placeholders not resolvable or resource not found when trying to open it
			if (ignoreResourceNotFound) {
				if (logger.isInfoEnabled()) {
					logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
				}
			}
			else {
				throw ex;
			}
		}
	}
}
 
Example 6
Source File: KeyValueRepositoryConfigurationExtension.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * Detects the query creator type to be used for the factory to set. Will lookup a {@link QueryCreatorType} annotation
 * on the {@code @Enable}-annotation or use {@link SpelQueryCreator} if not found.
 *
 * @param config
 * @return
 */
private static Class<?> getQueryType(AnnotationRepositoryConfigurationSource config) {

	AnnotationMetadata metadata = config.getEnableAnnotationMetadata();

	Map<String, Object> queryCreatorAnnotationAttributes = metadata
			.getAnnotationAttributes(QueryCreatorType.class.getName());

	if (queryCreatorAnnotationAttributes == null) {
		return KeyValuePartTreeQuery.class;
	}

	AnnotationAttributes queryCreatorAttributes = new AnnotationAttributes(queryCreatorAnnotationAttributes);
	return queryCreatorAttributes.getClass("repositoryQueryType");
}
 
Example 7
Source File: ByPluginNameEanbledCondition.java    From onetwo with Apache License 2.0 5 votes vote down vote up
private WebPlugin parsePlugin(AnnotationAttributes attributes){
	WebPlugin webPlugin = this.webPlugin;
	if(webPlugin==null){
		Class<? extends WebPlugin> pluginClass = attributes.getClass("pluginClass");
		/*if(pluginClass==WebPlugin.class){
			throw new BaseException("you must be set your plugin class to annotation @"+EnabledByPluginNameProperty.class.getSimpleName());
		}*/
		webPlugin = ReflectUtils.newInstance(pluginClass);
		this.webPlugin = webPlugin;
	}
	return webPlugin;
}
 
Example 8
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
	String name = propertySource.getString("name");
	if (!StringUtils.hasLength(name)) {
		name = null;
	}
	String encoding = propertySource.getString("encoding");
	if (!StringUtils.hasLength(encoding)) {
		encoding = null;
	}
	String[] locations = propertySource.getStringArray("value");
	Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
	boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

	Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
	PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
			DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

	for (String location : locations) {
		try {
			String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
			Resource resource = this.resourceLoader.getResource(resolvedLocation);
			addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
		}
		catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
			// Placeholders not resolvable or resource not found when trying to open it
			if (ignoreResourceNotFound) {
				if (logger.isInfoEnabled()) {
					logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
				}
			}
			else {
				throw ex;
			}
		}
	}
}
 
Example 9
Source File: AlfrescoRestRegistrar.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
private void processDispatcherWebscript(AnnotationAttributes webscriptAttributes, BeanDefinitionRegistry registry) {
	String webscript = webscriptAttributes.getString("name");
	Assert.hasText(webscript, "Webscript name cannot be empty!");

	Class<?> servletContext = webscriptAttributes.getClass("servletContext");

	ServletConfigOptions[] servletConfigOptions = (ServletConfigOptions[]) webscriptAttributes
			.get("servletConfigOptions");
	Class<? extends WebApplicationContext> servletContextClass = webscriptAttributes
			.getClass("servletContextClass");
	HttpMethod[] httpMethods = (HttpMethod[]) webscriptAttributes.get("httpMethods");
	boolean inheritGlobalProperties = (Boolean) webscriptAttributes.get("inheritGlobalProperties");

	GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
	beanDefinition.setBeanClass(DispatcherWebscript.class);

	DispatcherWebscript ws = new DispatcherWebscript(webscript, inheritGlobalProperties);
	ws.setContextClass(servletContextClass);
	ws.setContextConfigLocation(servletContext.getName());
	ws.addServletConfigOptions(servletConfigOptions);
	beanDefinition.setInstanceSupplier(() -> ws);
	beanDefinition.setRole(BeanDefinition.ROLE_APPLICATION);

	registry.registerBeanDefinition(webscript, beanDefinition);

	for (HttpMethod httpMethod : httpMethods) {
		registry.registerAlias(webscript, getWebscriptName(webscript, httpMethod));
	}
}
 
Example 10
Source File: MessageSenderEndpointBeanRegistrar.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Override
protected void registerBeanDefinitions(final String channelName,
                                       final String beanName,
                                       final AnnotationAttributes annotationAttributes,
                                       final BeanDefinitionRegistry registry) {
        final Class<? extends Selector> channelSelector = annotationAttributes.getClass("selector");
        final MessageFormat messageFormat = annotationAttributes.getEnum("messageFormat");

        if (!registry.containsBeanDefinition(beanName)) {
            registry.registerBeanDefinition(
                    beanName,
                    genericBeanDefinition(DelegateMessageSenderEndpoint.class)
                            .addConstructorArgValue(channelName)
                            .addConstructorArgValue(channelSelector)
                            .addConstructorArgValue(messageFormat)
                            .setDependencyCheck(DEPENDENCY_CHECK_ALL)
                            .getBeanDefinition()
            );

            LOG.info("Registered MessageQueueSenderEndpoint {} with for channelName {}, messageFormat {}", beanName, channelName, messageFormat);
        } else {
            throw new BeanCreationException(
                    beanName,
                    format("MessageQueueReceiverEndpoint %s is already registered.", beanName)
            );
        }
}
 
Example 11
Source File: RemoteServiceScannerRegistrar.java    From seed with Apache License 2.0 4 votes vote down vote up
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    for(BeanDefinitionHolder holder : beanDefinitions){
        try {
            //获取每个标注了@RemoteService注解的所有属性及其值,得到一个Map
            MetadataReader metadataReader = this.getMetadataReaderFactory().getMetadataReader(holder.getBeanDefinition().getBeanClassName());
            AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(metadataReader.getAnnotationMetadata().getAnnotationAttributes(RemoteService.class.getName()));
            if(null==annoAttrs || annoAttrs.isEmpty()){
                continue;
            }
            //计算serviceInterface
            Class<?> serviceInterface = annoAttrs.getClass("value");
            if(null == serviceInterface){
                serviceInterface = annoAttrs.getClass("serviceInterface");
            }
            if("java.lang.Class".equals(serviceInterface.getName())){
                throw new IllegalArgumentException("undefined service interface on RemoteService class: " + holder.getBeanDefinition().getBeanClassName());
            }
            //计算服务路径("/" + path + "/" + name)
            String name = annoAttrs.getString("name").trim();
            if(StringUtils.isBlank(name)){
                name = serviceInterface.getSimpleName();
            }
            String path = annoAttrs.getString("path").trim();
            if(StringUtils.isNotBlank(path)){
                if(path.endsWith("/")){
                    name = path + name;
                }else{
                    name = path + "/" + name;
                }
            }
            if(!name.startsWith("/")){
                name = "/" + name;
            }
            //通过Spring提供的HttpInvokerServiceExporter输出服务,该类可以将普通Bean实例输出成远程服务
            //这里是比较关键的:因为我们需要自己设定哪个Bean输出服务,哪个Bean不用输出,所以才自定义注解来实现
            //@RemoteServiceScan和@RemoteService的目的就是找到我们希望输出服务的Bean,然后手工注册Bean并输出
            GenericBeanDefinition definition = new GenericBeanDefinition();
            definition.getPropertyValues().add("service", new RuntimeBeanReference(holder.getBeanName()));
            definition.getPropertyValues().add("serviceInterface", serviceInterface);
            definition.setInitMethodName("afterPropertiesSet");
            definition.setBeanClass(HttpInvokerServiceExporter.class);
            this.registerBeanDefinition(new BeanDefinitionHolder(definition, name), this.getRegistry());
        }catch(IOException e){
            throw new BeanDefinitionStoreException("Failed to read candidate component class: " + holder.getBeanDefinition().getBeanClassName(), e);
        }
    }
}
 
Example 12
Source File: ConfigurationClassParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Apply processing and build a complete {@link ConfigurationClass} by reading the
 * annotations, members and methods from the source class. This method can be called
 * multiple times as relevant sources are discovered.
 * @param configClass the configuration class being build
 * @param sourceClass a source class
 * @return the superclass, or {@code null} if none found or previously processed
 */
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {

	// Recursively process any member (nested) classes first
	processMemberClasses(configClass, sourceClass);

	// Process any @PropertySource annotations
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
		else {
			logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
					"]. Reason: Environment must implement ConfigurableEnvironment");
		}
	}

	// Process any @ComponentScan annotations
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(
						holder.getBeanDefinition(), this.metadataReaderFactory)) {
					parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	// Process any @ImportResource annotations
	if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
		AnnotationAttributes importResource =
				AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
	processInterfaces(configClass, sourceClass);

	// Process superclass, if any
	if (sourceClass.getMetadata().hasSuperClass()) {
		String superclass = sourceClass.getMetadata().getSuperClassName();
		if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
			this.knownSuperclasses.put(superclass, configClass);
			// Superclass found, return its annotation metadata and recurse
			return sourceClass.getSuperClass();
		}
	}

	// No superclass -> processing is complete
	return null;
}
 
Example 13
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);
}
 
Example 14
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 15
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Apply processing and build a complete {@link ConfigurationClass} by reading the
 * annotations, members and methods from the source class. This method can be called
 * multiple times as relevant sources are discovered.
 * @param configClass the configuration class being build
 * @param sourceClass a source class
 * @return the superclass, or {@code null} if none found or previously processed
 */
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {

	if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
		// Recursively process any member (nested) classes first
		processMemberClasses(configClass, sourceClass);
	}

	// Process any @PropertySource annotations
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
		else {
			logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
					"]. Reason: Environment must implement ConfigurableEnvironment");
		}
	}

	// Process any @ComponentScan annotations
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
				if (bdCand == null) {
					bdCand = holder.getBeanDefinition();
				}
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
					parse(bdCand.getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	// Process any @ImportResource annotations
	AnnotationAttributes importResource =
			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
	if (importResource != null) {
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
	processInterfaces(configClass, sourceClass);

	// Process superclass, if any
	if (sourceClass.getMetadata().hasSuperClass()) {
		String superclass = sourceClass.getMetadata().getSuperClassName();
		if (superclass != null && !superclass.startsWith("java") &&
				!this.knownSuperclasses.containsKey(superclass)) {
			this.knownSuperclasses.put(superclass, configClass);
			// Superclass found, return its annotation metadata and recurse
			return sourceClass.getSuperClass();
		}
	}

	// No superclass -> processing is complete
	return null;
}
 
Example 16
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Apply processing and build a complete {@link ConfigurationClass} by reading the
 * annotations, members and methods from the source class. This method can be called
 * multiple times as relevant sources are discovered.
 * @param configClass the configuration class being build
 * @param sourceClass a source class
 * @return the superclass, or {@code null} if none found or previously processed
 */
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {

	if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
		// Recursively process any member (nested) classes first
		processMemberClasses(configClass, sourceClass);
	}

	// Process any @PropertySource annotations
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
		else {
			logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
					"]. Reason: Environment must implement ConfigurableEnvironment");
		}
	}

	// Process any @ComponentScan annotations
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
				if (bdCand == null) {
					bdCand = holder.getBeanDefinition();
				}
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
					parse(bdCand.getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	// Process any @ImportResource annotations
	AnnotationAttributes importResource =
			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
	if (importResource != null) {
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
	processInterfaces(configClass, sourceClass);

	// Process superclass, if any
	if (sourceClass.getMetadata().hasSuperClass()) {
		String superclass = sourceClass.getMetadata().getSuperClassName();
		if (superclass != null && !superclass.startsWith("java") &&
				!this.knownSuperclasses.containsKey(superclass)) {
			this.knownSuperclasses.put(superclass, configClass);
			// Superclass found, return its annotation metadata and recurse
			return sourceClass.getSuperClass();
		}
	}

	// No superclass -> processing is complete
	return null;
}
 
Example 17
Source File: ContextConfigurationAttributes.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"),
			annAttrs.getBoolean("inheritLocations"),
			(Class<? extends ApplicationContextInitializer<?>>[]) annAttrs.getClassArray("initializers"),
			annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), annAttrs.getClass("loader"));
}
 
Example 18
Source File: ContextConfigurationAttributes.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"), annAttrs.getBoolean("inheritLocations"),
		(Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[]) annAttrs.getClassArray("initializers"),
		annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), (Class<? extends ContextLoader>) annAttrs.getClass("loader"));
}
 
Example 19
Source File: ContextConfigurationAttributes.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"),
			annAttrs.getBoolean("inheritLocations"),
			(Class<? extends ApplicationContextInitializer<?>>[]) annAttrs.getClassArray("initializers"),
			annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), annAttrs.getClass("loader"));
}
 
Example 20
Source File: DubboConfigBindingRegistrar.java    From dubbo-2.6.5 with Apache License 2.0 3 votes vote down vote up
protected void registerBeanDefinitions(AnnotationAttributes attributes, BeanDefinitionRegistry registry) {

//        解析prefix属性,可以用占位符
        String prefix = environment.resolvePlaceholders(attributes.getString("prefix"));

//        type属性值,AbstractConfig的实现类
        Class<? extends AbstractConfig> configClass = attributes.getClass("type");

        boolean multiple = attributes.getBoolean("multiple");

//        注册dubbo配置属性=》
        registerDubboConfigBeans(prefix, configClass, multiple, registry);

    }