Java Code Examples for org.springframework.beans.factory.config.BeanDefinitionHolder#getBeanDefinition()

The following examples show how to use org.springframework.beans.factory.config.BeanDefinitionHolder#getBeanDefinition() . 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: CustomNamespaceHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
	Element element = (Element) node;
	BeanDefinition def = definition.getBeanDefinition();

	MutablePropertyValues mpvs = (def.getPropertyValues() == null) ? new MutablePropertyValues() : def.getPropertyValues();
	mpvs.add("name", element.getAttribute("name"));
	mpvs.add("age", element.getAttribute("age"));

	((AbstractBeanDefinition) def).setPropertyValues(mpvs);
	return definition;
}
 
Example 2
Source File: RpcInvokerAnnotationScanner.java    From hasting with MIT License 5 votes vote down vote up
@Override
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	HashSet<BeanDefinitionHolder> beans = new HashSet<BeanDefinitionHolder>();
	Set<BeanDefinitionHolder> set = super.doScan(basePackages);
	for(BeanDefinitionHolder bdh:set){
		GenericBeanDefinition bdf = (GenericBeanDefinition)bdh.getBeanDefinition();
		bdf.getPropertyValues().add("invokerInterface", bdf.getBeanClassName());
		bdf.getPropertyValues().add("rpcClientCache", rpcClients);
		bdf.setBeanClass(RpcInvokerFactoryBean.class);
	}
	return beans;
}
 
Example 3
Source File: CustomNamespaceHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
	Element element = (Element) node;
	BeanDefinition def = definition.getBeanDefinition();

	MutablePropertyValues mpvs = (def.getPropertyValues() == null) ? new MutablePropertyValues() : def.getPropertyValues();
	mpvs.add("name", element.getAttribute("name"));
	mpvs.add("age", element.getAttribute("age"));

	((AbstractBeanDefinition) def).setPropertyValues(mpvs);
	return definition;
}
 
Example 4
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 5
Source File: QualifierAnnotationAutowireCandidateResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on qualified element, if any
		Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
		// Then, check annotation on factory method, if applicable
		if (targetAnnotation == null) {
			targetAnnotation = getFactoryMethodAnnotation(bd, type);
		}
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				try {
					Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
					if (beanType != null) {
						targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Not the usual case - simply forget about the type check...
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 6
Source File: ScopedProxyUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Generate a scoped proxy for the supplied target bean, registering the target
 * bean with an internal name and setting 'targetBeanName' on the scoped proxy.
 * @param definition the original bean definition
 * @param registry the bean definition registry
 * @param proxyTargetClass whether to create a target class proxy
 * @return the scoped proxy definition
 */
public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition,
		BeanDefinitionRegistry registry, boolean proxyTargetClass) {

	String originalBeanName = definition.getBeanName();
	BeanDefinition targetDefinition = definition.getBeanDefinition();
	String targetBeanName = getTargetBeanName(originalBeanName);

	// Create a scoped proxy definition for the original bean name,
	// "hiding" the target bean in an internal target definition.
	RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
	proxyDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, targetBeanName));
	proxyDefinition.setOriginatingBeanDefinition(targetDefinition);
	proxyDefinition.setSource(definition.getSource());
	proxyDefinition.setRole(targetDefinition.getRole());

	proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName);
	if (proxyTargetClass) {
		targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
		// ScopedProxyFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here.
	}
	else {
		proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE);
	}

	// Copy autowire settings from original bean definition.
	proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
	proxyDefinition.setPrimary(targetDefinition.isPrimary());
	if (targetDefinition instanceof AbstractBeanDefinition) {
		proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
	}

	// The target bean should be ignored in favor of the scoped proxy.
	targetDefinition.setAutowireCandidate(false);
	targetDefinition.setPrimary(false);

	// Register the target bean as separate bean in the factory.
	registry.registerBeanDefinition(targetBeanName, targetDefinition);

	// Return the scoped proxy definition as primary bean definition
	// (potentially an inner bean).
	return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());
}
 
Example 7
Source File: GenericTypeAwareAutowireCandidateResolver.java    From blog_demos with Apache License 2.0 4 votes vote down vote up
/**
 * Match the given dependency type with its generic type information against the given
 * candidate bean definition.
 */
protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
	ResolvableType dependencyType = descriptor.getResolvableType();
	if (dependencyType.getType() instanceof Class) {
		// No generic type -> we know it's a Class type-match, so no need to check again.
		return true;
	}
	ResolvableType targetType = null;
	RootBeanDefinition rbd = null;
	if (bdHolder.getBeanDefinition() instanceof RootBeanDefinition) {
		rbd = (RootBeanDefinition) bdHolder.getBeanDefinition();
	}
	if (rbd != null) {
		// First, check factory method return type, if applicable
		targetType = getReturnTypeForFactoryMethod(rbd, descriptor);
		if (targetType == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(rbd);
			if (dbd != null) {
				targetType = getReturnTypeForFactoryMethod(dbd, descriptor);
			}
		}
	}
	if (targetType == null) {
		// Regular case: straight bean instance, with BeanFactory available.
		if (this.beanFactory != null) {
			Class<?> beanType = this.beanFactory.getType(bdHolder.getBeanName());
			if (beanType != null) {
				targetType = ResolvableType.forClass(ClassUtils.getUserClass(beanType));
			}
		}
		// Fallback: no BeanFactory set, or no type resolvable through it
		// -> best-effort match against the target class if applicable.
		if (targetType == null && rbd != null && rbd.hasBeanClass() && rbd.getFactoryMethodName() == null) {
			Class<?> beanClass = rbd.getBeanClass();
			if (!FactoryBean.class.isAssignableFrom(beanClass)) {
				targetType = ResolvableType.forClass(ClassUtils.getUserClass(beanClass));
			}
		}
	}
	if (targetType == null || (descriptor.fallbackMatchAllowed() && targetType.hasUnresolvableGenerics())) {
		return true;
	}
	// Full check for complex generic type match...
	return dependencyType.isAssignableFrom(targetType);
}
 
Example 8
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getType(@Nonnull String beanName) throws NoSuchBeanDefinitionException {
    Optional<Class<?>> opt = beanTypeCache.get(beanName);
    //noinspection OptionalAssignedToNull
    if (opt == null) {
        final BeanDefinitionReference<?> definition = beanDefinitionMap.get(beanName);
        if (definition != null) {
            opt = Optional.of(definition.getBeanType());
        } else {

            beanName = transformedBeanName(beanName);
            // Check manually registered singletons.
            Object beanInstance = super.getSingleton(beanName, false);
            if (beanInstance != null && !beanInstance.getClass().getSimpleName().equals("NullBean")) {
                if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(beanName)) {
                    return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
                } else {
                    return beanInstance.getClass();
                }
            }
            // No singleton instance found -> check bean definition.
            org.springframework.beans.factory.BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // No bean definition found in this factory -> delegate to parent.
                return parentBeanFactory.getType(originalBeanName(beanName));
            }

            final org.springframework.beans.factory.config.BeanDefinition parentDef;
            try {
                parentDef = super.getBeanDefinition(beanName);
            } catch (NoSuchBeanDefinitionException e) {
                beanTypeCache.put(beanName, Optional.empty());
                return null;
            }
            if (parentDef instanceof RootBeanDefinition) {

                RootBeanDefinition mbd = (RootBeanDefinition) parentDef;

                // Check decorated bean definition, if any: We assume it'll be easier
                // to determine the decorated bean's type than the proxy's type.
                BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
                if (dbd != null && !BeanFactoryUtils.isFactoryDereference(beanName)) {
                    RootBeanDefinition tbd = super.getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
                    Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
                    if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
                        return targetClass;
                    }
                }

                Class<?> beanClass = predictBeanType(beanName, mbd);

                // Check bean class whether we're dealing with a FactoryBean.
                if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
                    if (!BeanFactoryUtils.isFactoryDereference(beanName)) {
                        // If it's a FactoryBean, we want to look at what it creates, not at the factory class.
                        return super.getTypeForFactoryBean(beanName, mbd);
                    } else {
                        return beanClass;
                    }
                } else {
                    return (!BeanFactoryUtils.isFactoryDereference(beanName) ? beanClass : null);
                }
            }
        }
        beanTypeCache.put(beanName, opt);
    }

    return opt.orElse(null);
}
 
Example 9
Source File: QualifierAnnotationAutowireCandidateResolver.java    From blog_demos with Apache License 2.0 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on factory method, if applicable
		Annotation targetAnnotation = getFactoryMethodAnnotation(bd, type);
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
				if (beanType != null) {
					targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 10
Source File: QualifierAnnotationAutowireCandidateResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on qualified element, if any
		Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
		// Then, check annotation on factory method, if applicable
		if (targetAnnotation == null) {
			targetAnnotation = getFactoryMethodAnnotation(bd, type);
		}
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				try {
					Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
					if (beanType != null) {
						targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Not the usual case - simply forget about the type check...
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 11
Source File: ConfigurationClassBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Read the given {@link BeanMethod}, registering bean definitions
 * with the BeanDefinitionRegistry based on its contents.
 */
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
	ConfigurationClass configClass = beanMethod.getConfigurationClass();
	MethodMetadata metadata = beanMethod.getMetadata();
	String methodName = metadata.getMethodName();

	// Do we need to mark the bean as skipped by its condition?
	if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
		configClass.skippedBeanMethods.add(methodName);
		return;
	}
	if (configClass.skippedBeanMethods.contains(methodName)) {
		return;
	}

	// Consider name and any aliases
	AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
	List<String> names = new ArrayList<String>(Arrays.asList(bean.getStringArray("name")));
	String beanName = (names.size() > 0 ? names.remove(0) : methodName);

	// Register aliases even when overridden
	for (String alias : names) {
		this.registry.registerAlias(beanName, alias);
	}

	// Has this effectively been overridden before (e.g. via XML)?
	if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
		return;
	}

	ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
	beanDef.setResource(configClass.getResource());
	beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

	if (metadata.isStatic()) {
		// static @Bean method
		beanDef.setBeanClassName(configClass.getMetadata().getClassName());
		beanDef.setFactoryMethodName(methodName);
	}
	else {
		// instance @Bean method
		beanDef.setFactoryBeanName(configClass.getBeanName());
		beanDef.setUniqueFactoryMethodName(methodName);
	}
	beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

	AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

	Autowire autowire = bean.getEnum("autowire");
	if (autowire.isAutowire()) {
		beanDef.setAutowireMode(autowire.value());
	}

	String initMethodName = bean.getString("initMethod");
	if (StringUtils.hasText(initMethodName)) {
		beanDef.setInitMethodName(initMethodName);
	}

	String destroyMethodName = bean.getString("destroyMethod");
	if (destroyMethodName != null) {
		beanDef.setDestroyMethodName(destroyMethodName);
	}

	// Consider scoping
	ScopedProxyMode proxyMode = ScopedProxyMode.NO;
	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
	if (attributes != null) {
		beanDef.setScope(attributes.getAliasedString("value", Scope.class, configClass.getResource()));
		proxyMode = attributes.getEnum("proxyMode");
		if (proxyMode == ScopedProxyMode.DEFAULT) {
			proxyMode = ScopedProxyMode.NO;
		}
	}

	// Replace the original bean definition with the target one, if necessary
	BeanDefinition beanDefToRegister = beanDef;
	if (proxyMode != ScopedProxyMode.NO) {
		BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
				new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS);
		beanDefToRegister = new ConfigurationClassBeanDefinition(
				(RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Registering bean definition for @Bean method %s.%s()",
				configClass.getMetadata().getClassName(), beanName));
	}

	this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}
 
Example 12
Source File: ConfigurationClassBeanDefinitionReader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read the given {@link BeanMethod}, registering bean definitions
 * with the BeanDefinitionRegistry based on its contents.
 */
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
	ConfigurationClass configClass = beanMethod.getConfigurationClass();
	MethodMetadata metadata = beanMethod.getMetadata();
	String methodName = metadata.getMethodName();

	// Do we need to mark the bean as skipped by its condition?
	if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
		configClass.skippedBeanMethods.add(methodName);
		return;
	}
	if (configClass.skippedBeanMethods.contains(methodName)) {
		return;
	}

	// Consider name and any aliases
	AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
	List<String> names = new ArrayList<String>(Arrays.asList(bean.getStringArray("name")));
	String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

	// Register aliases even when overridden
	for (String alias : names) {
		this.registry.registerAlias(beanName, alias);
	}

	// Has this effectively been overridden before (e.g. via XML)?
	if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
		if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
			throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
					beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() +
					"' clashes with bean name for containing configuration class; please make those names unique!");
		}
		return;
	}

	ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
	beanDef.setResource(configClass.getResource());
	beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

	if (metadata.isStatic()) {
		// static @Bean method
		beanDef.setBeanClassName(configClass.getMetadata().getClassName());
		beanDef.setFactoryMethodName(methodName);
	}
	else {
		// instance @Bean method
		beanDef.setFactoryBeanName(configClass.getBeanName());
		beanDef.setUniqueFactoryMethodName(methodName);
	}
	beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

	AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

	Autowire autowire = bean.getEnum("autowire");
	if (autowire.isAutowire()) {
		beanDef.setAutowireMode(autowire.value());
	}

	String initMethodName = bean.getString("initMethod");
	if (StringUtils.hasText(initMethodName)) {
		beanDef.setInitMethodName(initMethodName);
	}

	String destroyMethodName = bean.getString("destroyMethod");
	if (destroyMethodName != null) {
		beanDef.setDestroyMethodName(destroyMethodName);
	}

	// Consider scoping
	ScopedProxyMode proxyMode = ScopedProxyMode.NO;
	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
	if (attributes != null) {
		beanDef.setScope(attributes.getString("value"));
		proxyMode = attributes.getEnum("proxyMode");
		if (proxyMode == ScopedProxyMode.DEFAULT) {
			proxyMode = ScopedProxyMode.NO;
		}
	}

	// Replace the original bean definition with the target one, if necessary
	BeanDefinition beanDefToRegister = beanDef;
	if (proxyMode != ScopedProxyMode.NO) {
		BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
				new BeanDefinitionHolder(beanDef, beanName), this.registry,
				proxyMode == ScopedProxyMode.TARGET_CLASS);
		beanDefToRegister = new ConfigurationClassBeanDefinition(
				(RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Registering bean definition for @Bean method %s.%s()",
				configClass.getMetadata().getClassName(), beanName));
	}

	this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}
 
Example 13
Source File: GroovyBeanDefinitionWrapper.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public void setBeanDefinitionHolder(BeanDefinitionHolder holder) {
	this.definition = (AbstractBeanDefinition) holder.getBeanDefinition();
	this.beanName = holder.getBeanName();
}
 
Example 14
Source File: GroovyBeanDefinitionWrapper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void setBeanDefinitionHolder(BeanDefinitionHolder holder) {
	this.definition = (AbstractBeanDefinition) holder.getBeanDefinition();
	this.beanName = holder.getBeanName();
}
 
Example 15
Source File: GroovyBeanDefinitionWrapper.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public void setBeanDefinitionHolder(BeanDefinitionHolder holder) {
	this.definition = (AbstractBeanDefinition) holder.getBeanDefinition();
	this.beanName = holder.getBeanName();
}
 
Example 16
Source File: AnnotationBean.java    From spring-boot-starter-dubbo with Apache License 2.0 4 votes vote down vote up
private Class<?> resolveClass(BeanDefinitionHolder beanDefinitionHolder) {
    BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition();
    return resolveClass(beanDefinition);

}
 
Example 17
Source File: QualifierAnnotationAutowireCandidateResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on qualified element, if any
		Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
		// Then, check annotation on factory method, if applicable
		if (targetAnnotation == null) {
			targetAnnotation = getFactoryMethodAnnotation(bd, type);
		}
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				try {
					Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
					if (beanType != null) {
						targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Not the usual case - simply forget about the type check...
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 18
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 19
Source File: ScopedProxyUtils.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Generate a scoped proxy for the supplied target bean, registering the target
 * bean with an internal name and setting 'targetBeanName' on the scoped proxy.
 * @param definition the original bean definition
 * @param registry the bean definition registry
 * @param proxyTargetClass whether to create a target class proxy
 * @return the scoped proxy definition
 */
public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition,
		BeanDefinitionRegistry registry, boolean proxyTargetClass) {

	String originalBeanName = definition.getBeanName();
	BeanDefinition targetDefinition = definition.getBeanDefinition();
	String targetBeanName = getTargetBeanName(originalBeanName);

	// Create a scoped proxy definition for the original bean name,
	// "hiding" the target bean in an internal target definition.
	RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
	proxyDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, targetBeanName));
	proxyDefinition.setOriginatingBeanDefinition(targetDefinition);
	proxyDefinition.setSource(definition.getSource());
	proxyDefinition.setRole(targetDefinition.getRole());

	proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName);
	if (proxyTargetClass) {
		targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
		// ScopedProxyFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here.
	}
	else {
		proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE);
	}

	// Copy autowire settings from original bean definition.
	proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
	proxyDefinition.setPrimary(targetDefinition.isPrimary());
	if (targetDefinition instanceof AbstractBeanDefinition) {
		proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
	}

	// The target bean should be ignored in favor of the scoped proxy.
	targetDefinition.setAutowireCandidate(false);
	targetDefinition.setPrimary(false);

	// Register the target bean as separate bean in the factory.
	registry.registerBeanDefinition(targetBeanName, targetDefinition);

	// Return the scoped proxy definition as primary bean definition
	// (potentially an inner bean).
	return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());
}
 
Example 20
Source File: FeignClientToDubboProviderBeanPostProcessor.java    From spring-cloud-alibaba-dubbo with Apache License 2.0 3 votes vote down vote up
private Class<?> resolveClass(BeanDefinitionHolder beanDefinitionHolder) {

        BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition();

        return resolveClass(beanDefinition);

    }