org.springframework.beans.factory.support.AbstractBeanDefinition Java Examples

The following examples show how to use org.springframework.beans.factory.support.AbstractBeanDefinition. 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: BeanRegistrar.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
/**
 * registers beans within the current application context of the given class with the given parameters
 *
 * @param beanClass             Class of the bean to be generated
 * @param beanName              unique name of the bean to be generated
 * @param constructorValues     Set of Objects, which will be passed as contructor values
 * @param constructorReferences Set of Object which will be passed as constructor references
 * @param propertyValues        Map of String,Object which will be passed to the key (property) name as value
 * @param propertyReferences    Map of String,Object which will be passed to the key (property) name as reference
 * @param dependsOnBeans        Set of Strings, which contains depending bean names
 */
public void registerBean(final Class<?> beanClass, final String beanName,
                         final Set<Object> constructorValues,
                         final Set<String> constructorReferences,
                         final Map<String, Object> propertyValues,
                         final Map<String, String> propertyReferences,
                         final Set<String> dependsOnBeans) {
    final BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
    builder.setAutowireMode(AbstractBeanDefinition.DEPENDENCY_CHECK_ALL);
    addConstructorArgReferences(builder, constructorReferences);
    addConstructorArgValues(builder, constructorValues);
    addPropertyReference(builder, propertyReferences);
    addPropertyValues(builder, propertyValues);
    addDependsOnBean(builder, dependsOnBeans);
    final DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();
    factory.registerBeanDefinition(beanName, builder.getBeanDefinition());
}
 
Example #2
Source File: BeanDefinitionParserDelegate.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public int getAutowireMode(String attValue) {
	String att = attValue;
	if (DEFAULT_VALUE.equals(att)) {
		att = this.defaults.getAutowire();
	}
	int autowire = AbstractBeanDefinition.AUTOWIRE_NO;
	if (AUTOWIRE_BY_NAME_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_NAME;
	}
	else if (AUTOWIRE_BY_TYPE_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_TYPE;
	}
	else if (AUTOWIRE_CONSTRUCTOR_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR;
	}
	else if (AUTOWIRE_AUTODETECT_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_AUTODETECT;
	}
	// Else leave default value.
	return autowire;
}
 
Example #3
Source File: GroovyBeanDefinitionWrapper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected AbstractBeanDefinition createBeanDefinition() {
	AbstractBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(this.clazz);
	if (!CollectionUtils.isEmpty(this.constructorArgs)) {
		ConstructorArgumentValues cav = new ConstructorArgumentValues();
		for (Object constructorArg : this.constructorArgs) {
			cav.addGenericArgumentValue(constructorArg);
		}
		bd.setConstructorArgumentValues(cav);
	}
	if (this.parentName != null) {
		bd.setParentName(this.parentName);
	}
	this.definitionWrapper = new BeanWrapperImpl(bd);
	return bd;
}
 
Example #4
Source File: RedissonDefinitionParser.java    From redisson with Apache License 2.0 6 votes vote down vote up
private void parseConfigTypes(Element element, String configType, BeanDefinitionBuilder redissonDef, ParserContext parserContext) {
    BeanDefinitionBuilder builder
            = helper.createBeanDefinitionBuilder(element,
                    parserContext, null);
    //Use factory method on the Config bean
    AbstractBeanDefinition bd = builder.getRawBeanDefinition();
    bd.setFactoryMethodName("use" + StringUtils.capitalize(configType));
    bd.setFactoryBeanName(parserContext.getContainingComponent().getName());
    String id = parserContext.getReaderContext().generateBeanName(bd);
    helper.registerBeanDefinition(builder, id,
            helper.parseAliase(element), parserContext);
    helper.parseAttributes(element, parserContext, builder);
    redissonDef.addDependsOn(id);
    parseChildElements(element, id, null, redissonDef, parserContext);
    parserContext.getDelegate().parseQualifierElements(element, bd);
}
 
Example #5
Source File: BeanDefinitionParserDelegate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
public int getAutowireMode(String attValue) {
	String att = attValue;
	if (isDefaultValue(att)) {
		att = this.defaults.getAutowire();
	}
	int autowire = AbstractBeanDefinition.AUTOWIRE_NO;
	if (AUTOWIRE_BY_NAME_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_NAME;
	}
	else if (AUTOWIRE_BY_TYPE_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_TYPE;
	}
	else if (AUTOWIRE_CONSTRUCTOR_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR;
	}
	else if (AUTOWIRE_AUTODETECT_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_AUTODETECT;
	}
	// Else leave default value.
	return autowire;
}
 
Example #6
Source File: NettyRpcClientBeanDefinitionRegistrar.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
private void registerNettyRpcClient(AnnotatedBeanDefinition beanDefinition,BeanDefinitionRegistry registry)  {
    AnnotationMetadata metadata = beanDefinition.getMetadata();
    Map<String, Object> nettyRpcClientAttributes = metadata.getAnnotationAttributes(nettyRpcClientCanonicalName);
    Map<String, Object> lazyAttributes = metadata.getAnnotationAttributes(lazyCanonicalName);

    Class<?> beanClass;
    try {
        beanClass = ClassUtils.forName(metadata.getClassName(), classLoader);
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException("NettyRpcClientsRegistrar failure! notfound class",e);
    }

    String serviceName = resolve((String) nettyRpcClientAttributes.get("serviceName"));
    beanDefinition.setLazyInit(lazyAttributes == null || Boolean.TRUE.equals(lazyAttributes.get("value")));
    ((AbstractBeanDefinition)beanDefinition).setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    ((AbstractBeanDefinition)beanDefinition).setInstanceSupplier(newInstanceSupplier(beanClass,serviceName,(int)nettyRpcClientAttributes.get("timeout")));

    String beanName = generateBeanName(beanDefinition.getBeanClassName());
    registry.registerBeanDefinition(beanName,beanDefinition);
}
 
Example #7
Source File: AbstractApiClentRegistrar.java    From onetwo with Apache License 2.0 6 votes vote down vote up
/***
	 * @see RestApiClientConfiguration#apiClientRestExecutor()
	 * @author wayshall
	 * @param annotationMetadataHelper
	 * @param registry
	 */
	@Deprecated
	protected void regiseterRestExecutor(AnnotationMetadataHelper annotationMetadataHelper, BeanDefinitionRegistry registry){
		if(registry.containsBeanDefinition(RestExecutorFactory.REST_EXECUTOR_FACTORY_BEAN_NAME)){
			return ;
		}
		Class<?> restExecutorFacotryClass = (Class<?>)annotationMetadataHelper.getAttributes().get(ATTRS_REST_EXECUTOR_FACTORY);
//		RestExecutorFactory factory = null;
		if(restExecutorFacotryClass==null || restExecutorFacotryClass==RestExecutorFactory.class){
			restExecutorFacotryClass = DefaultRestExecutorFactory.class;
		}
		BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(restExecutorFacotryClass);
		definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
		registry.registerBeanDefinition(RestExecutorFactory.REST_EXECUTOR_FACTORY_BEAN_NAME, definition.getBeanDefinition());
		
	}
 
Example #8
Source File: ConfigBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does <strong>not</strong>
 * parse any associated '{@code pointcut}' or '{@code pointcut-ref}' attributes.
 */
private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
	RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
	advisorDefinition.setSource(parserContext.extractSource(advisorElement));

	String adviceRef = advisorElement.getAttribute(ADVICE_REF);
	if (!StringUtils.hasText(adviceRef)) {
		parserContext.getReaderContext().error(
				"'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
	}
	else {
		advisorDefinition.getPropertyValues().add(
				ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef));
	}

	if (advisorElement.hasAttribute(ORDER_PROPERTY)) {
		advisorDefinition.getPropertyValues().add(
				ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY));
	}

	return advisorDefinition;
}
 
Example #9
Source File: AuthDataAccessor.java    From syncope with Apache License 2.0 6 votes vote down vote up
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
    synchronized (this) {
        if (jwtSSOProviders == null) {
            jwtSSOProviders = new HashMap<>();

            implementationLookup.getJWTSSOProviderClasses().stream().
                    map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
                    createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
                    forEach(jwtSSOProvider -> jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider));
        }
    }

    if (issuer == null) {
        throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
    }
    JWTSSOProvider provider = jwtSSOProviders.get(issuer);
    if (provider == null) {
        throw new AuthenticationCredentialsNotFoundException(
                "Could not find any registered JWTSSOProvider for issuer " + issuer);
    }

    return provider;
}
 
Example #10
Source File: AccessPointBeanDefinitionParser.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    String id = element.getAttribute(ATTRIBUTE_ID);
    String url = element.getAttribute(ATTRIBUTE_URL);

    Assert.hasText(url, String.format("%s can not be blank", ATTRIBUTE_URL));

    if (!StringUtils.hasText(id)) {
        id = OMSSpringConsts.DEFAULT_ACCESS_POINT_ID;
    }

    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(AccessPointContainer.class)
            .addConstructorArgValue(id)
            .addConstructorArgValue(url);
    List<BeanDefinition> attributes = parseAttributes(beanDefinitionBuilder, element, parserContext);
    beanDefinitionBuilder.addConstructorArgValue(attributes);

    AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
    parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
    return beanDefinition;
}
 
Example #11
Source File: ShardingStrategyBeanDefinitionParser.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    String type = element.getLocalName();
    switch (type) {
        case ShardingStrategyBeanDefinitionTag.STANDARD_STRATEGY_ROOT_TAG:
            return getStandardShardingStrategyConfigBeanDefinition(element);
        case ShardingStrategyBeanDefinitionTag.COMPLEX_STRATEGY_ROOT_TAG:
            return getComplexShardingStrategyConfigBeanDefinition(element);
        case ShardingStrategyBeanDefinitionTag.HINT_STRATEGY_ROOT_TAG:
            return getHintShardingStrategyConfigBeanDefinition(element);
        case ShardingStrategyBeanDefinitionTag.NONE_STRATEGY_ROOT_TAG:
            return getNoneShardingStrategyConfigBeanDefinition();
        default:
            throw new ShardingSphereException("Cannot support type: %s", type);
    }
}
 
Example #12
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 #13
Source File: DatasourceBeanDefinitionRegistry.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
                                                                              throws BeansException {
    BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder
        .genericBeanDefinition(HikariDataSource.class);
    AbstractBeanDefinition beanDefinition = definitionBuilder.getRawBeanDefinition();
    beanDefinition.setDestroyMethodName("close");
    beanDefinition.setPrimary(false);

    definitionBuilder.addPropertyValue("driverClassName", "org.h2.Driver");
    definitionBuilder
        .addPropertyValue(
            "jdbcUrl",
            "jdbc:mysql://1.1.1.1:3306/xxx?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull");
    definitionBuilder.addPropertyValue("username", "sofa");
    definitionBuilder.addPropertyValue("password", "123456");

    registry.registerBeanDefinition("manualDataSource",
        definitionBuilder.getRawBeanDefinition());
}
 
Example #14
Source File: ComponentBeanDefinitionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static AbstractBeanDefinition parseComponentElement(Element element) {
	BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(ComponentFactoryBean.class);
	factory.addPropertyValue("parent", parseComponent(element));

	List<Element> childElements = DomUtils.getChildElementsByTagName(element, "component");
	if (!CollectionUtils.isEmpty(childElements)) {
		parseChildComponents(childElements, factory);
	}

	return factory.getBeanDefinition();
}
 
Example #15
Source File: MqBeanParser.java    From zxl with Apache License 2.0 5 votes vote down vote up
protected void buildRabbitTemplateBeanDefinition(String beanName, String connectionFactoryBeanName, BeanDefinitionRegistry beanDefinitionRegistry) {
	AbstractBeanDefinition rabbitTemplateBeanDefinition = new GenericBeanDefinition();
	rabbitTemplateBeanDefinition.setBeanClass(RabbitTemplate.class);
	ConstructorArgumentValues rabbitTemplateConstructorArgumentValues = new ConstructorArgumentValues();
	rabbitTemplateConstructorArgumentValues.addIndexedArgumentValue(0, new RuntimeBeanReference(connectionFactoryBeanName));
	rabbitTemplateBeanDefinition.setConstructorArgumentValues(rabbitTemplateConstructorArgumentValues);
	beanDefinitionRegistry.registerBeanDefinition(beanName, rabbitTemplateBeanDefinition);
}
 
Example #16
Source File: MBeanServerBeanDefinitionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
static AbstractBeanDefinition findServerForSpecialEnvironment() {
	if (weblogicPresent) {
		RootBeanDefinition bd = new RootBeanDefinition(JndiObjectFactoryBean.class);
		bd.getPropertyValues().add("jndiName", "java:comp/env/jmx/runtime");
		return bd;
	}
	else if (webspherePresent) {
		return new RootBeanDefinition(WebSphereMBeanServerFactoryBean.class);
	}
	else {
		return null;
	}
}
 
Example #17
Source File: ConfigBeanDefinitionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Parses the supplied {@code <pointcut>} and registers the resulting
 * Pointcut with the BeanDefinitionRegistry.
 */
private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) {
	String id = pointcutElement.getAttribute(ID);
	String expression = pointcutElement.getAttribute(EXPRESSION);

	AbstractBeanDefinition pointcutDefinition = null;

	try {
		this.parseState.push(new PointcutEntry(id));
		pointcutDefinition = createPointcutDefinition(expression);
		pointcutDefinition.setSource(parserContext.extractSource(pointcutElement));

		String pointcutBeanName = id;
		if (StringUtils.hasText(pointcutBeanName)) {
			parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition);
		}
		else {
			pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition);
		}

		parserContext.registerComponent(
				new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression));
	}
	finally {
		this.parseState.pop();
	}

	return pointcutDefinition;
}
 
Example #18
Source File: NacosPropertySourceBeanDefinitionParser.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(Element element,
		ParserContext parserContext) {

	BeanDefinitionRegistry registry = parserContext.getRegistry();
	// Register Dependent Beans
	registerNacosPropertySourcePostProcessor(registry);
	registerXmlNacosPropertySourceBuilder(registry);

	NacosPropertySourceXmlBeanDefinition beanDefinition = new NacosPropertySourceXmlBeanDefinition();
	beanDefinition.setElement(element);
	beanDefinition.setXmlReaderContext(parserContext.getReaderContext());

	return beanDefinition;
}
 
Example #19
Source File: CosmosRepositoryConfigurationExtension.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
@Override
public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConfigurationSource config) {
    super.registerBeansForRoot(registry, config);

    if (!registry.containsBeanDefinition(Constants.COSMOS_MAPPING_CONTEXT)) {
        final RootBeanDefinition definition = new RootBeanDefinition(CosmosMappingContext.class);
        definition.setRole(AbstractBeanDefinition.ROLE_INFRASTRUCTURE);
        definition.setSource(config.getSource());

        registry.registerBeanDefinition(Constants.COSMOS_MAPPING_CONTEXT, definition);
    }
}
 
Example #20
Source File: FeignClientToDubboProviderBeanPostProcessor.java    From spring-cloud-alibaba-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * Registers {@link ServiceBean} from new annotated {@link Service} {@link BeanDefinition}
 *
 * @param beanDefinitionHolder
 * @param registry
 * @param scanner
 * @see ServiceBean
 * @see BeanDefinition
 */
private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, BeanDefinitionRegistry registry,
                                 DubboClassPathBeanDefinitionScanner scanner) {

    Class<?> beanClass = resolveClass(beanDefinitionHolder);

    Service service = findAnnotation(beanClass, Service.class);
    if (null == service) {
        service = this.defaultService;
    }

    Class<?> interfaceClass = resolveServiceInterfaceClass(beanClass, service);

    String annotatedServiceBeanName = beanDefinitionHolder.getBeanName();

    AbstractBeanDefinition serviceBeanDefinition =
            buildServiceBeanDefinition(service, interfaceClass, annotatedServiceBeanName);

    // ServiceBean Bean name
    String beanName = generateServiceBeanName(service, interfaceClass, annotatedServiceBeanName);

    if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean
        registry.registerBeanDefinition(beanName, serviceBeanDefinition);

        if (logger.isInfoEnabled()) {
            logger.warn("The BeanDefinition[" + serviceBeanDefinition +
                    "] of ServiceBean has been registered with name : " + beanName);
        }

    } else {

        if (logger.isWarnEnabled()) {
            logger.warn("The Duplicated BeanDefinition[" + serviceBeanDefinition +
                    "] of ServiceBean[ bean name : " + beanName +
                    "] was be found , Did @DubboComponentScan scan to same package in many times?");
        }

    }

}
 
Example #21
Source File: ClassPathBeanDefinitionScanner.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Apply further settings to the given bean definition,
 * beyond the contents retrieved from scanning the component class.
 * @param beanDefinition the scanned bean definition
 * @param beanName the generated bean name for the given bean
 */
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
	beanDefinition.applyDefaults(this.beanDefinitionDefaults);
	if (this.autowireCandidatePatterns != null) {
		beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
	}
}
 
Example #22
Source File: CachingListenerValidatorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Resolves class of a beanDefinition
 * @param beanDefinition the bean definition
 * @return class of the bean definition
 * @throws IllegalStateException if the given bean definition class can not
 * be resolved
 * @see org.springframework.beans.factory.config.BeanDefinition#setBeanClassName(String)
 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#resolveBeanClass(ClassLoader)
 */
protected Class resolveBeanClass(BeanDefinition beanDefinition)
		throws IllegalStateException {
	try {
		return ((AbstractBeanDefinition) beanDefinition)
				.resolveBeanClass(ClassUtils.getDefaultClassLoader());
	} catch (ClassNotFoundException e) {
		throw new IllegalStateException("Could not resolve class ["
				+ beanDefinition.getBeanClassName() + "] of caching listener");
	}
}
 
Example #23
Source File: AbstractSingleBeanDefinitionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a {@link BeanDefinitionBuilder} instance for the
 * {@link #getBeanClass bean Class} and passes it to the
 * {@link #doParse} strategy method.
 * @param element the element that is to be parsed into a single BeanDefinition
 * @param parserContext the object encapsulating the current state of the parsing process
 * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
 * @throws IllegalStateException if the bean {@link Class} returned from
 * {@link #getBeanClass(org.w3c.dom.Element)} is {@code null}
 * @see #doParse
 */
@Override
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	String parentName = getParentName(element);
	if (parentName != null) {
		builder.getRawBeanDefinition().setParentName(parentName);
	}
	Class<?> beanClass = getBeanClass(element);
	if (beanClass != null) {
		builder.getRawBeanDefinition().setBeanClass(beanClass);
	}
	else {
		String beanClassName = getBeanClassName(element);
		if (beanClassName != null) {
			builder.getRawBeanDefinition().setBeanClassName(beanClassName);
		}
	}
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	if (parserContext.isNested()) {
		// Inner bean definition must receive same scope as containing bean.
		builder.setScope(parserContext.getContainingBeanDefinition().getScope());
	}
	if (parserContext.isDefaultLazyInit()) {
		// Default-lazy-init applies to custom bean definitions as well.
		builder.setLazyInit(true);
	}
	doParse(element, parserContext, builder);
	return builder.getBeanDefinition();
}
 
Example #24
Source File: ActivitiAnnotationDrivenBeanDefinitionParser.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private void registerProcessScope(Element element, ParserContext parserContext) {
	Class clz = ProcessScope.class;
	BeanDefinitionBuilder processScopeBDBuilder = BeanDefinitionBuilder.genericBeanDefinition(clz);
	AbstractBeanDefinition scopeBeanDefinition = processScopeBDBuilder.getBeanDefinition();
	scopeBeanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	configureProcessEngine(scopeBeanDefinition, element);
	String beanName = baseBeanName(clz);
	parserContext.getRegistry().registerBeanDefinition(beanName, scopeBeanDefinition);
}
 
Example #25
Source File: EmbeddedDatabaseBeanDefinitionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(EmbeddedDatabaseFactoryBean.class);
	setGenerateUniqueDatabaseNameFlag(element, builder);
	setDatabaseName(element, builder);
	setDatabaseType(element, builder);
	DatabasePopulatorConfigUtils.setDatabasePopulator(element, builder);
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	return builder.getBeanDefinition();
}
 
Example #26
Source File: EmbeddedDatabaseBeanDefinitionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(EmbeddedDatabaseFactoryBean.class);
	setGenerateUniqueDatabaseNameFlag(element, builder);
	setDatabaseName(element, builder);
	setDatabaseType(element, builder);
	DatabasePopulatorConfigUtils.setDatabasePopulator(element, builder);
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	return builder.getBeanDefinition();
}
 
Example #27
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 #28
Source File: Simple2RestApiClentRegistrar.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
protected BeanDefinitionBuilder createApiClientFactoryBeanBuilder(AnnotationMetadata annotationMetadata, AnnotationAttributes attributes) {
	String className = annotationMetadata.getClassName();
	BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(DefaultApiClientFactoryBean.class);

	definition.addPropertyValue("url", resolveUrl(attributes));
	definition.addPropertyValue("path", resolvePath(attributes));
	definition.addPropertyValue("interfaceClass", className);
	definition.addPropertyReference("restExecutor", RestExecutorFactory.REST_EXECUTOR_FACTORY_BEAN_NAME);
	definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
	
	return definition;
}
 
Example #29
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testScopingBeanToUnregisteredScopeResultsInAnException() throws Exception {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
	AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
	beanDefinition.setScope("he put himself so low could hardly look me in the face");

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("testBean", beanDefinition);
	factory.getBean("testBean");
}
 
Example #30
Source File: CustomNamespaceHandlerTests.java    From java-technology-stack 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;
}