org.springframework.beans.factory.config.BeanDefinitionHolder Java Examples

The following examples show how to use org.springframework.beans.factory.config.BeanDefinitionHolder. 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: SimplePropertyNamespaceHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
	if (node instanceof Attr) {
		Attr attr = (Attr) node;
		String propertyName = parserContext.getDelegate().getLocalName(attr);
		String propertyValue = attr.getValue();
		MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues();
		if (pvs.contains(propertyName)) {
			parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " +
					"both <property> and inline syntax. Only one approach may be used per property.", attr);
		}
		if (propertyName.endsWith(REF_SUFFIX)) {
			propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length());
			pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue));
		}
		else {
			pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue);
		}
	}
	return definition;
}
 
Example #2
Source File: RequestScopedProxyTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testGetAnonymousInnerBeanFromScope() throws Exception {
	TestBean bean = (TestBean) this.beanFactory.getBean("outerBean");
	assertFalse(AopUtils.isAopProxy(bean));
	assertTrue(AopUtils.isCglibProxy(bean.getSpouse()));

	BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean");
	BeanDefinitionHolder innerBeanDef =
			(BeanDefinitionHolder) beanDef.getPropertyValues().getPropertyValue("spouse").getValue();
	String name = innerBeanDef.getBeanName();

	MockHttpServletRequest request = new MockHttpServletRequest();
	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		assertNull(request.getAttribute("scopedTarget." + name));
		assertEquals("scoped", bean.getSpouse().getName());
		assertNotNull(request.getAttribute("scopedTarget." + name));
		assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass());
		assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
	}
	finally {
		RequestContextHolder.setRequestAttributes(null);
	}
}
 
Example #3
Source File: CuratorFrameworkBeanDefinitionParser.java    From zookeeper-spring with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
  final BeanDefinitionBuilder beanDefBuilder = BeanDefinitionBuilder.rootBeanDefinition(CuratorFrameworkFactoryBean.class);
  beanDefBuilder.setRole(ROLE_APPLICATION);
  beanDefBuilder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
  
  beanDefBuilder.addPropertyValue("connectString", element.getAttribute("connect-string"));
  
  Element retryPolicyElement = DomUtils.getChildElementByTagName(element, "retry-policy");
  if (retryPolicyElement != null) {
    Element retryPolicyBeanElement = DomUtils.getChildElements(retryPolicyElement).get(0);
    BeanDefinitionHolder retryPolicy = parserContext.getDelegate().parseBeanDefinitionElement(retryPolicyBeanElement, beanDefBuilder.getBeanDefinition());
    beanDefBuilder.addPropertyValue("retryPolicy", retryPolicy);
  }

  Node namespace = element.getAttributeNode("namespace");
  if (namespace != null) {
    beanDefBuilder.addPropertyValue("namespace", namespace.getNodeValue());
  }

  return beanDefBuilder.getBeanDefinition();
}
 
Example #4
Source File: AnnotationBeanDefinitionRegistryPostProcessor.java    From spring-context-support with Apache License 2.0 6 votes vote down vote up
/**
 * Scan and register the primary {@link BeanDefinition BeanDefinitions} that were annotated by
 * {@link #getSupportedAnnotationTypes() the supported annotation types}, and then return the {@link Map} with bean name plus
 * aliases if present and primary {@link AnnotatedBeanDefinition AnnotatedBeanDefinitions}.
 * <p>
 * Current method is allowed to be override by the sub-class to change the registration logic
 *
 * @param scanner      {@link ExposingClassPathBeanDefinitionScanner}
 * @param basePackages the base packages to scan
 * @return the {@link Map} with bean name plus aliases if present and primary
 * {@link AnnotatedBeanDefinition AnnotatedBeanDefinitions}
 */
protected Map<String, AnnotatedBeanDefinition> registerPrimaryBeanDefinitions(ExposingClassPathBeanDefinitionScanner scanner,
                                                                              String[] basePackages) {
    // Scan and register
    Set<BeanDefinitionHolder> primaryBeanDefinitionHolders = scanner.doScan(basePackages);
    // Log the primary BeanDefinitions
    logPrimaryBeanDefinitions(primaryBeanDefinitionHolders, basePackages);

    Map<String, AnnotatedBeanDefinition> primaryBeanDefinitions = new LinkedHashMap<String, AnnotatedBeanDefinition>();

    for (BeanDefinitionHolder beanDefinitionHolder : primaryBeanDefinitionHolders) {
        putPrimaryBeanDefinitions(primaryBeanDefinitions, beanDefinitionHolder);
    }

    // return
    return primaryBeanDefinitions;
}
 
Example #5
Source File: SimplePropertyNamespaceHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
	if (node instanceof Attr) {
		Attr attr = (Attr) node;
		String propertyName = parserContext.getDelegate().getLocalName(attr);
		String propertyValue = attr.getValue();
		MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues();
		if (pvs.contains(propertyName)) {
			parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " +
					"both <property> and inline syntax. Only one approach may be used per property.", attr);
		}
		if (propertyName.endsWith(REF_SUFFIX)) {
			propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length());
			pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue));
		}
		else {
			pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue);
		}
	}
	return definition;
}
 
Example #6
Source File: ComponentScanBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected void registerComponents(
		XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {

	Object source = readerContext.extractSource(element);
	CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);

	for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
		compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
	}

	// Register annotation config processors, if necessary.
	boolean annotationConfig = true;
	if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
		annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
	}
	if (annotationConfig) {
		Set<BeanDefinitionHolder> processorDefinitions =
				AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
		for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
			compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
		}
	}

	readerContext.fireComponentRegistered(compositeDef);
}
 
Example #7
Source File: AbstractHasorDefinitionParser.java    From hasor with Apache License 2.0 6 votes vote down vote up
/**摘抄 Spring 源码,将Bean注册到容器中*/
private BeanDefinition registerBean(Element element, ParserContext parserContext, NamedNodeMap attributes, AbstractBeanDefinition definition) {
    if (!parserContext.isNested()) {
        try {
            String id = beanID(element, attributes);
            if (!StringUtils.hasText(id)) {
                parserContext.getReaderContext().error(beanID(element, attributes) + " is undefined. for element '" + element.getLocalName(), element);
            }
            BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id);
            BeanDefinitionReaderUtils.registerBeanDefinition(holder, parserContext.getRegistry());
            parserContext.registerComponent(new BeanComponentDefinition(holder));
        } catch (BeanDefinitionStoreException ex) {
            parserContext.getReaderContext().error(ex.getMessage(), element);
            return null;
        }
    }
    return definition;
}
 
Example #8
Source File: QualifierAnnotationAutowireContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutowiredMethodParameterWithStaticallyQualifiedCandidate() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs = new ConstructorArgumentValues();
	cavs.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person = new RootBeanDefinition(QualifiedPerson.class, cavs, null);
	context.registerBeanDefinition(JUERGEN,
			ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(person, JUERGEN), context, true).getBeanDefinition());
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	context.refresh();
	QualifiedMethodParameterTestBean bean =
			(QualifiedMethodParameterTestBean) context.getBean("autowired");
	assertEquals(JUERGEN, bean.getPerson().getName());
}
 
Example #9
Source File: AnnotationDrivenBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private ManagedList<?> getCallableInterceptors(
		Element element, @Nullable Object source, ParserContext context) {

	ManagedList<Object> interceptors = new ManagedList<>();
	Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support");
	if (asyncElement != null) {
		Element interceptorsElement = DomUtils.getChildElementByTagName(asyncElement, "callable-interceptors");
		if (interceptorsElement != null) {
			interceptors.setSource(source);
			for (Element converter : DomUtils.getChildElementsByTagName(interceptorsElement, "bean")) {
				BeanDefinitionHolder beanDef = context.getDelegate().parseBeanDefinitionElement(converter);
				if (beanDef != null) {
					beanDef = context.getDelegate().decorateBeanDefinitionIfRequired(converter, beanDef);
					interceptors.add(beanDef);
				}
			}
		}
	}
	return interceptors;
}
 
Example #10
Source File: AnnotationDrivenBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
	ManagedList<Object> result = new ManagedList<>();
	for (Object object : list) {
		if (object instanceof BeanDefinitionHolder) {
			BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
			String className = beanDef.getBeanDefinition().getBeanClassName();
			Assert.notNull(className, "No resolver class");
			Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());
			if (WebArgumentResolver.class.isAssignableFrom(clazz)) {
				RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class);
				adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef);
				result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter"));
				continue;
			}
		}
		result.add(object);
	}
	return result;
}
 
Example #11
Source File: AnnotationDrivenBeanDefinitionParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ManagedList<?> getCallableInterceptors(Element element, Object source, ParserContext parserContext) {
	ManagedList<? super Object> interceptors = new ManagedList<Object>();
	Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support");
	if (asyncElement != null) {
		Element interceptorsElement = DomUtils.getChildElementByTagName(asyncElement, "callable-interceptors");
		if (interceptorsElement != null) {
			interceptors.setSource(source);
			for (Element converter : DomUtils.getChildElementsByTagName(interceptorsElement, "bean")) {
				BeanDefinitionHolder beanDef = parserContext.getDelegate().parseBeanDefinitionElement(converter);
				beanDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(converter, beanDef);
				interceptors.add(beanDef);
			}
		}
	}
	return interceptors;
}
 
Example #12
Source File: BeanDefinitionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void beanDefinitionHolderEquality() {
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setAbstract(true);
	bd.setLazyInit(true);
	bd.setScope("request");
	BeanDefinitionHolder holder = new BeanDefinitionHolder(bd, "bd");
	RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class);
	assertTrue(!bd.equals(otherBd));
	assertTrue(!otherBd.equals(bd));
	otherBd.setAbstract(true);
	otherBd.setLazyInit(true);
	otherBd.setScope("request");
	BeanDefinitionHolder otherHolder = new BeanDefinitionHolder(bd, "bd");
	assertTrue(holder.equals(otherHolder));
	assertTrue(otherHolder.equals(holder));
	assertTrue(holder.hashCode() == otherHolder.hashCode());
}
 
Example #13
Source File: BeanDefinitionParserDelegate.java    From java-technology-stack with MIT License 6 votes vote down vote up
public BeanDefinitionHolder decorateIfRequired(
		Node node, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) {

	String namespaceUri = getNamespaceURI(node);
	if (namespaceUri != null && !isDefaultNamespace(namespaceUri)) {
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler != null) {
			BeanDefinitionHolder decorated =
					handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
			if (decorated != null) {
				return decorated;
			}
		}
		else if (namespaceUri.startsWith("http://www.springframework.org/")) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node);
		}
		else {
			// A custom namespace, not to be handled by Spring - maybe "xml:...".
			if (logger.isDebugEnabled()) {
				logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]");
			}
		}
	}
	return originalDef;
}
 
Example #14
Source File: AbstractRetrofitClientsRegistrar.java    From spring-cloud-square with Apache License 2.0 6 votes vote down vote up
private void registerRetrofitClient(BeanDefinitionRegistry registry,
								 AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
	String className = annotationMetadata.getClassName();
	BeanDefinitionBuilder definition = BeanDefinitionBuilder
			.genericBeanDefinition(getFactoryBeanClass());
	validate(attributes);
	definition.addPropertyValue("url", getUrl(attributes));
	String name = getName(attributes);
	definition.addPropertyValue("name", name);
	definition.addPropertyValue("type", className);
	definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

	String alias = name + "RetrofitClient";
	AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
	beanDefinition.setPrimary(true);

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

	BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
			new String[] { alias });
	BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
 
Example #15
Source File: BeanDefinitionReaderUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Register the given bean definition with the given bean factory.
 * @param definitionHolder the bean definition including name and aliases
 * @param registry the bean factory to register with
 * @throws BeanDefinitionStoreException if registration failed
 */
public static void registerBeanDefinition(
		BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
		throws BeanDefinitionStoreException {

	// Register bean definition under primary name.
	String beanName = definitionHolder.getBeanName();
	registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

	// Register aliases for bean name, if any.
	String[] aliases = definitionHolder.getAliases();
	if (aliases != null) {
		for (String alias : aliases) {
			registry.registerAlias(beanName, alias);
		}
	}
}
 
Example #16
Source File: FactoryBeanNodeExecutor.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 解析Node完整流程
 * 
 * @param zookeeperTemplate
 * @param source
 * @return
 * @throws UnifiedConfigException
 * @throws IOException
 * @throws ZookeeperExpcetion
 */
public List<BeanDefinitionHolder> doExecuteInBox(
		ZookeeperTemplate zookeeperTemplate, String source)
		throws UnifiedConfigException, IOException, ZookeeperExpcetion {

	// default properties
	OverrideProperties defaultProperties = getDefaultProperties(defaultPropertiesShortName);

	// read zk
	byte[] data = zookeeperTemplate.readData(znode);
	String propertiesString = new String(data);
	Properties p = defaultProperties.overrideProperties(new StringReader(
			propertiesString));
	checkProperties(p);

	// create Bean
	return CollectionUtil.gList(createFactoryBeanDefinition(p));
}
 
Example #17
Source File: DefaultBeanDefinitionDocumentReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example #18
Source File: ConfigurationClassBeanDefinitionReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Register the {@link Configuration} class itself as a bean definition.
 */
private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) {
	AnnotationMetadata metadata = configClass.getMetadata();
	AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata);

	ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef);
	configBeanDef.setScope(scopeMetadata.getScopeName());
	String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry);
	AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata);

	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName);
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition());
	configClass.setBeanName(configBeanName);

	if (logger.isDebugEnabled()) {
		logger.debug("Registered bean definition for imported class '" + configBeanName + "'");
	}
}
 
Example #19
Source File: DictionaryBeanFactoryPostProcessor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Iterates through the set values and calls helpers to process the value
 *
 * @param setVal the set to process
 * @param propertyName name of the property which has the set value
 * @param nestedBeanStack stack of bean containers which contains the set property
 */
protected void visitSet(Set setVal, String propertyName, Stack<BeanDefinitionHolder> nestedBeanStack) {
    boolean isMergeEnabled = false;
    if (setVal instanceof ManagedSet) {
        isMergeEnabled = ((ManagedSet) setVal).isMergeEnabled();
    }

    ManagedSet newSet = new ManagedSet();
    newSet.setMergeEnabled(isMergeEnabled);

    for (Object elem : setVal) {
        if (isStringValue(elem)) {
            elem = processSetStringPropertyValue(propertyName, setVal, getString(elem), nestedBeanStack,
                    beanProcessors);
        } else {
            elem = visitPropertyValue(propertyName, elem, nestedBeanStack);
        }

        newSet.add(elem);
    }

    setVal.clear();
    setVal.addAll(newSet);
}
 
Example #20
Source File: NamespaceHandlerSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Decorates the supplied {@link Node} by delegating to the {@link BeanDefinitionDecorator} that
 * is registered to handle that {@link Node}.
 */
@Override
@Nullable
public BeanDefinitionHolder decorate(
		Node node, BeanDefinitionHolder definition, ParserContext parserContext) {

	BeanDefinitionDecorator decorator = findDecoratorForNode(node, parserContext);
	return (decorator != null ? decorator.decorate(node, definition, parserContext) : null);
}
 
Example #21
Source File: AbstractImportRegistrar.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected void registerComponent(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, AnnotationAttributes tagAttributes) {
	String className = annotationMetadata.getClassName();
	String beanName = resolveName(tagAttributes, className);
	if(logger.isInfoEnabled()){
		logger.info("register api client beanName: {}, class: {}", beanName, className);
	}
	
	BeanDefinitionBuilder definition = createComponentFactoryBeanBuilder(annotationMetadata, tagAttributes);
	
	String alias = beanName + "-" + getComponentAnnotationClass().getSimpleName();
	AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
	beanDefinition.setPrimary(true);
	BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, beanName, new String[] { alias });
	BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
 
Example #22
Source File: CustomSchemaParser.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Parses a bean of the custom namespace.
 *
 * @param tag - The Element to be parsed.
 * @param parent - The parent bean that the tag is nested in.
 * @param parserContext - Provided information and functionality regarding current bean set.
 * @return The parsed bean.
 */
protected Object parseCustomBean(Element tag, BeanDefinitionBuilder parent, ParserContext parserContext) {
    BeanDefinition beanDefinition = parserContext.getDelegate().parseCustomElement(tag, parent.getBeanDefinition());

    String name = beanDefinition.getParentName() + "$Customchild" + beanNumber;
    if (tag.getAttribute("id") != null && !StringUtils.isEmpty(tag.getAttribute("id"))) {
        name = tag.getAttribute("id");
    } else {
        beanNumber++;
    }

    return new BeanDefinitionHolder(beanDefinition, name);
}
 
Example #23
Source File: ClassPathBeanDefinitionScanner.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Perform a scan within the specified base packages,
 * returning the registered bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 * @param basePackages the packages to check for annotated classes
 * @return set of beans registered if any for tooling registration purposes (never {@code null})
 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder =
						AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}
 
Example #24
Source File: DictionaryBeanFactoryPostProcessor.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Invokes the processors to handle an array string value (which may be changed)
 *
 * @param propertyName name of the property that is being processed
 * @param propertyValue the array which contains the string
 * @param elementValue the string element value
 * @param elementIndex the index of the string within the array
 * @param nestedBeanStack the stack of bean containers, including the bean that contains the property
 * @return String new property value (possibly modified by processors)
 */
protected String processArrayStringPropertyValue(String propertyName, Object[] propertyValue, String elementValue,
        int elementIndex, Stack<BeanDefinitionHolder> nestedBeanStack,
        List<DictionaryBeanProcessor> beanProcessors) {
    String processedStringValue = elementValue;

    for (DictionaryBeanProcessor beanProcessor : beanProcessors) {
        processedStringValue = beanProcessor.processArrayStringPropertyValue(propertyName, propertyValue,
                elementValue, elementIndex, nestedBeanStack);
    }

    return processedStringValue;
}
 
Example #25
Source File: ComponentScanBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
	basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
	String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
			ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

	// Actually scan for bean definitions and register them.
	ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
	Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
	registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

	return null;
}
 
Example #26
Source File: GenericTypeAwareAutowireCandidateResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected RootBeanDefinition getResolvedDecoratedDefinition(RootBeanDefinition rbd) {
	BeanDefinitionHolder decDef = rbd.getDecoratedDefinition();
	if (decDef != null && this.beanFactory instanceof ConfigurableListableBeanFactory) {
		ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory) this.beanFactory;
		if (clbf.containsBeanDefinition(decDef.getBeanName())) {
			BeanDefinition dbd = clbf.getMergedBeanDefinition(decDef.getBeanName());
			if (dbd instanceof RootBeanDefinition) {
				return (RootBeanDefinition) dbd;
			}
		}
	}
	return null;
}
 
Example #27
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 #28
Source File: ContextConfiguratorServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String concatNames(List<BeanDefinitionHolder> holders) {
	Iterator<BeanDefinitionHolder> it = holders.iterator();
	StringBuilder builder = new StringBuilder();
	while (it.hasNext()) {
		String part = it.next().getBeanName();
		builder.append(part);
		if (it.hasNext()) {
			builder.append(",");
		}
	}
	return builder.toString();
}
 
Example #29
Source File: ClassPathBeanDefinitionScanner.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform a scan within the specified base packages,
 * returning the registered bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 * @param basePackages the packages to check for annotated classes
 * @return set of beans registered if any for tooling registration purposes (never {@code null})
 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder =
						AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}
 
Example #30
Source File: CustomAutowireConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
	if (!bdHolder.getBeanDefinition().isAutowireCandidate()) {
		return false;
	}
	if (!bdHolder.getBeanName().matches("[a-z-]+")) {
		return false;
	}
	if (bdHolder.getBeanDefinition().getAttribute("priority").equals("1")) {
		return true;
	}
	return false;
}