Java Code Examples for org.springframework.beans.factory.support.BeanDefinitionBuilder#rootBeanDefinition()

The following examples show how to use org.springframework.beans.factory.support.BeanDefinitionBuilder#rootBeanDefinition() . 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: ServiceBeanParser.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Override
protected void parse(Element element, BeanDefinitionBuilder beanBuilder, ParserContext parserContext) throws ClassNotFoundException {
    String ref = element.getAttribute("ref");
    if (Strings.isNullOrEmpty(ref)) {
        String clzName = element.getAttribute("class");
        if (Strings.isNullOrEmpty(clzName)) {
            throw new EagleFrameException("Error both of ref and class is empty");
        }
        BeanDefinitionBuilder refBuilder = BeanDefinitionBuilder.rootBeanDefinition(clzName);
        parseProperties(element.getChildNodes(), refBuilder);
        String refId = parserContext.getReaderContext().generateBeanName(refBuilder.getBeanDefinition());
        parserContext.getRegistry().registerBeanDefinition(refId, refBuilder.getBeanDefinition());
        beanBuilder.addPropertyReference("ref", refId);
    }
    parseInterface(element, beanBuilder);

}
 
Example 2
Source File: MBeanExporterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("^&_invalidObjectName_(*", builder.getBeanDefinition());
	String exportedBeanName = "export.me.please";
	factory.registerSingleton(exportedBeanName, new TestBean());

	MBeanExporter exporter = new MBeanExporter();
	Map<String, Object> beansToExport = new HashMap<>();
	beansToExport.put(OBJECT_NAME, exportedBeanName);
	exporter.setBeans(beansToExport);
	exporter.setServer(getServer());
	exporter.setBeanFactory(factory);
	exporter.setAutodetectMode(MBeanExporter.AUTODETECT_NONE);
	// MBean has a bad ObjectName, so if said MBean is autodetected, an exception will be thrown...
	start(exporter);

}
 
Example 3
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 4
Source File: ConfigBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a '{@code declare-parents}' element and register the appropriate
 * DeclareParentsAdvisor with the BeanDefinitionRegistry encapsulated in the
 * supplied ParserContext.
 */
private AbstractBeanDefinition parseDeclareParents(Element declareParentsElement, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DeclareParentsAdvisor.class);
	builder.addConstructorArgValue(declareParentsElement.getAttribute(IMPLEMENT_INTERFACE));
	builder.addConstructorArgValue(declareParentsElement.getAttribute(TYPE_PATTERN));

	String defaultImpl = declareParentsElement.getAttribute(DEFAULT_IMPL);
	String delegateRef = declareParentsElement.getAttribute(DELEGATE_REF);

	if (StringUtils.hasText(defaultImpl) && !StringUtils.hasText(delegateRef)) {
		builder.addConstructorArgValue(defaultImpl);
	}
	else if (StringUtils.hasText(delegateRef) && !StringUtils.hasText(defaultImpl)) {
		builder.addConstructorArgReference(delegateRef);
	}
	else {
		parserContext.getReaderContext().error(
				"Exactly one of the " + DEFAULT_IMPL + " or " + DELEGATE_REF + " attributes must be specified",
				declareParentsElement, this.parseState.snapshot());
	}

	AbstractBeanDefinition definition = builder.getBeanDefinition();
	definition.setSource(parserContext.extractSource(declareParentsElement));
	parserContext.getReaderContext().registerWithGeneratedName(definition);
	return definition;
}
 
Example 5
Source File: NacosBeanUtils.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
/**
 * Register Infrastructure Bean
 *
 * @param registry {@link BeanDefinitionRegistry}
 * @param beanName the name of bean
 * @param beanClass the class of bean
 * @param constructorArgs the arguments of {@link Constructor}
 */
public static void registerInfrastructureBean(BeanDefinitionRegistry registry,
		String beanName, Class<?> beanClass, Object... constructorArgs) {
	// Build a BeanDefinition for NacosServiceFactory class
	BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
			.rootBeanDefinition(beanClass);
	for (Object constructorArg : constructorArgs) {
		beanDefinitionBuilder.addConstructorArgValue(constructorArg);
	}
	// ROLE_INFRASTRUCTURE
	beanDefinitionBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	// Register
	registry.registerBeanDefinition(beanName,
			beanDefinitionBuilder.getBeanDefinition());
}
 
Example 6
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 7
Source File: ShadowRuleBeanDefinitionParser.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Parse shadow rule element.
 * 
 * @param element element
 * @return bean definition of shadow rule
 */
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(ShadowRuleConfiguration.class);
    factory.addConstructorArgValue(element.getAttribute(ShadowDataSourceBeanDefinitionParserTag.COLUMN_CONFIG_TAG));
    factory.addConstructorArgValue(parseShadowMappings(DomUtils.getChildElementByTagName(element, ShadowDataSourceBeanDefinitionParserTag.MAPPINGS_CONFIG_TAG)));
    return factory.getBeanDefinition();
}
 
Example 8
Source File: MBeanExporterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-3625
public void testMBeanIsUnregisteredForRuntimeExceptionDuringInitialization() throws Exception {
	BeanDefinitionBuilder builder1 = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
	BeanDefinitionBuilder builder2 = BeanDefinitionBuilder
			.rootBeanDefinition(RuntimeExceptionThrowingConstructorBean.class);

	String objectName1 = "spring:test=bean1";
	String objectName2 = "spring:test=bean2";

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition(objectName1, builder1.getBeanDefinition());
	factory.registerBeanDefinition(objectName2, builder2.getBeanDefinition());

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(getServer());
	Map<String, Object> beansToExport = new HashMap<>();
	beansToExport.put(objectName1, objectName1);
	beansToExport.put(objectName2, objectName2);
	exporter.setBeans(beansToExport);
	exporter.setBeanFactory(factory);

	try {
		start(exporter);
		fail("Must have failed during creation of RuntimeExceptionThrowingConstructorBean");
	}
	catch (RuntimeException expected) {
	}

	assertIsNotRegistered("Must have unregistered all previously registered MBeans due to RuntimeException",
			ObjectNameManager.getInstance(objectName1));
	assertIsNotRegistered("Must have never registered this MBean due to RuntimeException",
			ObjectNameManager.getInstance(objectName2));
}
 
Example 9
Source File: MasterSlaveRuleBeanDefinitionParser.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(AlgorithmProvidedMasterSlaveRuleConfiguration.class);
    factory.addConstructorArgValue(parseMasterSlaveDataSourceRuleConfigurations(element));
    factory.addConstructorArgValue(ShardingSphereAlgorithmBeanRegistry.getAlgorithmBeanReferences(parserContext, MasterSlaveLoadBalanceAlgorithmFactoryBean.class));
    return factory.getBeanDefinition();
}
 
Example 10
Source File: ScriptFactoryPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static BeanDefinition createScriptFactoryPostProcessor(boolean isRefreshable) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ScriptFactoryPostProcessor.class);
	if (isRefreshable) {
		builder.addPropertyValue("defaultRefreshCheckDelay", new Long(1));
	}
	return builder.getBeanDefinition();
}
 
Example 11
Source File: UndertowHTTPServerEngineFactoryBeanDefinitionParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) {

    String bus = element.getAttribute("bus");

    BeanDefinitionBuilder factbean
        = BeanDefinitionBuilder
            .rootBeanDefinition(UndertowSpringTypesFactory.class);

    ctx.getRegistry()
        .registerBeanDefinition(UndertowSpringTypesFactory.class.getName(),
                                factbean.getBeanDefinition());
    try {
        if (StringUtils.isEmpty(bus)) {
            addBusWiringAttribute(bean, BusWiringType.CONSTRUCTOR);
        } else {
            bean.addConstructorArgReference(bus);
        }

        bean.addConstructorArgValue(mapElementToJaxbBean(element,
                                                    TLSServerParametersIdentifiedType.class,
                                                    UndertowSpringTypesFactory.class,
                                                    "createTLSServerParametersMap"));
        bean.addConstructorArgValue(mapElementToJaxbBean(element,
                                                    ThreadingParametersIdentifiedType.class,
                                                    UndertowSpringTypesFactory.class,
                            "createThreadingParametersMap"));

        // parser the engine list
        List<Object> list =
            getRequiredElementsList(element, ctx, new QName(HTTP_UNDERTOW_NS, "engine"), bean);
        if (!list.isEmpty()) {
            bean.addPropertyValue("enginesList", list);
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not process configuration.", e);
    }
}
 
Example 12
Source File: ShardingRuleBeanDefinitionParser.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private BeanDefinition parseAutoTableRuleConfiguration(final Element tableElement) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(ShardingAutoTableRuleConfiguration.class);
    factory.addConstructorArgValue(tableElement.getAttribute(ShardingRuleBeanDefinitionTag.LOGIC_TABLE_ATTRIBUTE));
    parseActualDataSources(tableElement, factory);
    parseShardingStrategyConfiguration(tableElement, factory);
    parseKeyGenerateStrategyConfiguration(tableElement, factory);
    return factory.getBeanDefinition();
}
 
Example 13
Source File: KeyGenerateStrategyBeanDefinitionParser.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(KeyGenerateStrategyConfiguration.class);
    factory.addConstructorArgValue(element.getAttribute(KeyGenerateStrategyBeanDefinitionTag.COLUMN_ATTRIBUTE));
    factory.addConstructorArgValue(element.getAttribute(KeyGenerateStrategyBeanDefinitionTag.ALGORITHM_REF_ATTRIBUTE));
    return factory.getBeanDefinition();
}
 
Example 14
Source File: AbstractJobBeanDefinitionParser.java    From shardingsphere-elasticjob-lite with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
@Override
protected final AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(JobScheduler.class);
    factory.setInitMethodName("init");
    factory.addConstructorArgReference(element.getAttribute(BaseJobBeanDefinitionParserTag.REGISTRY_CENTER_REF_ATTRIBUTE));
    factory.addConstructorArgReference(element.getAttribute(BaseJobBeanDefinitionParserTag.JOB_REF_ATTRIBUTE));
    factory.addConstructorArgValue(createJobConfiguration(element));
    BeanDefinition tracingConfig = createTracingConfiguration(element);
    if (null != tracingConfig) {
        factory.addConstructorArgValue(tracingConfig);
    }
    factory.addConstructorArgValue(createJobListeners(element));
    return factory.getBeanDefinition();
}
 
Example 15
Source File: StepBeanDefinitionRegistrar.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
		BeanDefinitionRegistry registry) {
	ComposedTaskProperties properties = composedTaskProperties();
	String ctrName = this.env.getProperty("spring.cloud.task.name");
	if(ctrName == null) {
		throw  new IllegalStateException("spring.cloud.task.name property must have a value.");
	}
	TaskParser taskParser = new TaskParser("bean-registration",
			properties.getGraph(), false, true);
	Map<String, Integer> taskSuffixMap = getTaskApps(taskParser);
	for (String taskName : taskSuffixMap.keySet()) {
		//handles the possibility that multiple instances of
		// task definition exist in a composed task
		for (int taskSuffix = 0; taskSuffixMap.get(taskName) >= taskSuffix; taskSuffix++) {
			BeanDefinitionBuilder builder = BeanDefinitionBuilder
					.rootBeanDefinition(ComposedTaskRunnerStepFactory.class);
			builder.addConstructorArgValue(properties);
			builder.addConstructorArgValue(String.format("%s_%s",
					taskName, taskSuffix));
			builder.addPropertyValue("taskSpecificProps",
					getPropertiesForTask(taskName, properties));
			String args = getCommandLineArgsForTask(properties.getComposedTaskArguments(), taskName, taskSuffixMap, ctrName);
			builder.addPropertyValue("arguments", args);
			registry.registerBeanDefinition(String.format("%s_%s",
					taskName, taskSuffix), builder.getBeanDefinition());
		}
	}
}
 
Example 16
Source File: HttpSolrClientBeanDefinitionParser.java    From dubbox with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(HttpSolrClientFactoryBean.class);
	setSolrHome(element, builder);
	return getSourcedBeanDefinition(builder, element, parserContext);
}
 
Example 17
Source File: DatasourceBeanDefinitionParser.java    From compass with Apache License 2.0 4 votes vote down vote up
/**
 * 解析主从库xml定义,构建主从库datasource
 * @param shardDataSourceId 数据源id
 * @param masterSlaveElement 数据源组节点
 * @param parserContext
 * @param dataSourcePrototypeAttributeValue  数据源原型
 * @param availabilityDetectorElement 心跳探测器节点
 * @param loadBalanceElement 负载均衡器节点
 * @return
 */
private AbstractBeanDefinition doCreateMasterSlaveDataSourceBeanDefinition(
		String shardDataSourceId,
		Element masterSlaveElement, 
		ParserContext parserContext,
		String dataSourcePrototypeAttributeValue,
		Element availabilityDetectorElement,
		Element loadBalanceElement,
		Element pingStatementElement) 
{
	String masterSlaveDataSourceId = masterSlaveElement.getAttribute(NAME);
	if(!StringUtils.hasText(masterSlaveDataSourceId))
	{
		throw new IllegalArgumentException("shardDataSourceId:["+shardDataSourceId+"],attribute '"+NAME+"' of element '"+GROUP+"' must be set!");
	}
    masterSlaveDataSourceId=masterSlaveDataSourceId.trim();
	BeanDefinitionBuilder masterSlaveDataSourceBeanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(MasterSlaveDataSource.class);
	masterSlaveDataSourceBeanDefinitionBuilder.addPropertyValue(ID, masterSlaveDataSourceId);
	masterSlaveDataSourceBeanDefinitionBuilder.addPropertyValue(MasterSlaveDataSource.SHARD_DATA_SOURCE_ID_PROPERTY_NAME, shardDataSourceId);
	
	//master必须设置
	Element masterElement = DomUtils.getChildElementByTagName(masterSlaveElement, MASTER);
	if(masterElement==null)
	{
		throw new IllegalArgumentException("shardDataSourceId:["+shardDataSourceId+"],Property '"+MASTER+"' of element '"+GROUP+"' must be set.");
	}
	
	this.parseMasterDataSource(
			masterElement, 
			masterSlaveDataSourceBeanDefinitionBuilder, 
			parserContext, 
			masterSlaveDataSourceId, 
			dataSourcePrototypeAttributeValue);
			
	
	//slave可以为空
	List<Element> slaveElements = DomUtils.getChildElementsByTagName(masterSlaveElement, SLAVE);
	if(!CollectionUtils.isEmpty(slaveElements))
	{
		this.parseSlaveDataSources(
				slaveElements,
				masterSlaveDataSourceBeanDefinitionBuilder, 
				parserContext, 
				masterSlaveDataSourceId, 
				dataSourcePrototypeAttributeValue);
	}
	
	
	//pingStatementElement可以为空
	if(pingStatementElement!=null)
	{
		String pingStatement=pingStatementElement.getAttribute(PINGSTATEMENT_VALUE);
		if(StringUtils.hasText(pingStatement))
		{
			masterSlaveDataSourceBeanDefinitionBuilder.addPropertyValue(MasterSlaveDataSource.PING_STATEMENT_PROPERTY_NAME, pingStatement.trim());
		}
	}
	
	//心跳探测器availabilityDetector可以为空,为空的时候不进行检测
	if(availabilityDetectorElement != null)
	{
		this.parseAvailabilityDetector(availabilityDetectorElement, masterSlaveDataSourceBeanDefinitionBuilder, parserContext);
	}
	
		
	//数据库负载均衡策略loadBalanceStrategy可以为空,为空的时候默认为WeightedRandom
	if(loadBalanceElement!=null)
	{
		this.parseLoadBalance(loadBalanceElement, masterSlaveDataSourceBeanDefinitionBuilder, parserContext);
	}
	
	
	return masterSlaveDataSourceBeanDefinitionBuilder.getBeanDefinition();
}
 
Example 18
Source File: HttpConduitBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Inject the "setTlsClientParameters" method with
 * a TLSClientParametersConfig object initialized with the JAXB
 * generated type unmarshalled from the selected node.
 */
public void mapTLSClientParameters(Element e, BeanDefinitionBuilder bean) {
    BeanDefinitionBuilder paramsbean
        = BeanDefinitionBuilder.rootBeanDefinition(TLSClientParametersConfig.TLSClientParametersTypeInternal.class);

    // read the attributes
    NamedNodeMap as = e.getAttributes();
    for (int i = 0; i < as.getLength(); i++) {
        Attr a = (Attr) as.item(i);
        if (a.getNamespaceURI() == null) {
            String aname = a.getLocalName();
            if ("useHttpsURLConnectionDefaultSslSocketFactory".equals(aname)
                || "useHttpsURLConnectionDefaultHostnameVerifier".equals(aname)
                || "disableCNCheck".equals(aname)
                || "enableRevocation".equals(aname)
                || "jsseProvider".equals(aname)
                || "secureSocketProtocol".equals(aname)
                || "sslCacheTimeout".equals(aname)) {
                paramsbean.addPropertyValue(aname, a.getValue());
            }
        }
    }

    // read the child elements
    Node n = e.getFirstChild();
    while (n != null) {
        if (Node.ELEMENT_NODE != n.getNodeType()
            || !SECURITY_NS.equals(n.getNamespaceURI())) {
            n = n.getNextSibling();
            continue;
        }
        String ename = n.getLocalName();
        // Schema should require that no more than one each of these exist.
        String ref = ((Element)n).getAttribute("ref");

        if ("keyManagers".equals(ename)) {
            if (ref != null && ref.length() > 0) {
                paramsbean.addPropertyReference("keyManagersRef", ref);
            } else {
                mapElementToJaxbProperty((Element)n, paramsbean, ename,
                                         KeyManagersType.class);
            }
        } else if ("trustManagers".equals(ename)) {
            if (ref != null && ref.length() > 0) {
                paramsbean.addPropertyReference("trustManagersRef", ref);
            } else {
                mapElementToJaxbProperty((Element)n, paramsbean, ename,
                                         TrustManagersType.class);
            }
        } else if ("cipherSuites".equals(ename)) {
            mapElementToJaxbProperty((Element)n, paramsbean, ename,
                                     CipherSuites.class);
        } else if ("cipherSuitesFilter".equals(ename)) {
            mapElementToJaxbProperty((Element)n, paramsbean, ename,
                                     FiltersType.class);
        } else if ("secureRandomParameters".equals(ename)) {
            mapElementToJaxbProperty((Element)n, paramsbean, ename,
                                     SecureRandomParameters.class);
        } else if ("certConstraints".equals(ename)) {
            mapElementToJaxbProperty((Element)n, paramsbean, ename,
                                     CertificateConstraintsType.class);
        } else if ("certAlias".equals(ename)) {
            paramsbean.addPropertyValue(ename, n.getTextContent());
        }
        n = n.getNextSibling();
    }

    BeanDefinitionBuilder jaxbbean
        = BeanDefinitionBuilder.rootBeanDefinition(TLSClientParametersConfig.class);
    jaxbbean.getRawBeanDefinition().setFactoryMethodName("createTLSClientParametersFromType");
    jaxbbean.addConstructorArgValue(paramsbean.getBeanDefinition());
    bean.addPropertyValue("tlsClientParameters", jaxbbean.getBeanDefinition());
}
 
Example 19
Source File: AbstractBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void mapElementToJaxbProperty(Element data,
                                        BeanDefinitionBuilder bean,
                                        String propertyName,
                                        Class<?> c) {
    try {
        XMLStreamWriter xmlWriter = null;
        Unmarshaller u = null;
        try {
            StringWriter writer = new StringWriter();
            xmlWriter = StaxUtils.createXMLStreamWriter(writer);
            StaxUtils.copy(data, xmlWriter);
            xmlWriter.flush();

            BeanDefinitionBuilder jaxbbean
                = BeanDefinitionBuilder.rootBeanDefinition(JAXBBeanFactory.class);
            jaxbbean.getRawBeanDefinition().setFactoryMethodName("createJAXBBean");
            jaxbbean.addConstructorArgValue(getContext(c));
            jaxbbean.addConstructorArgValue(writer.toString());
            jaxbbean.addConstructorArgValue(c);
            bean.addPropertyValue(propertyName, jaxbbean.getBeanDefinition());
        } catch (Exception ex) {
            u = getContext(c).createUnmarshaller();
            u.setEventHandler(null);
            Object obj;
            if (c != null) {
                obj = u.unmarshal(data, c);
            } else {
                obj = u.unmarshal(data);
            }
            if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>)obj;
                obj = el.getValue();
            }
            if (obj != null) {
                bean.addPropertyValue(propertyName, obj);
            }
        } finally {
            StaxUtils.close(xmlWriter);
            JAXBUtils.closeUnmarshaller(u);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse configuration.", e);
    }
}
 
Example 20
Source File: DataSourceBeanDefinitionParser.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(OrchestrationSpringShardingSphereDataSource.class);
    configureFactory(element, factory);
    return factory.getBeanDefinition();
}