Java Code Examples for org.springframework.beans.factory.support.BeanDefinitionBuilder

The following examples show how to use org.springframework.beans.factory.support.BeanDefinitionBuilder. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: BeanConfigurerSupportTests.java    License: MIT License 6 votes vote down vote up
@Test
public void configureBeanPerformsAutowiringByTypeIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception {
	TestBean beanInstance = new TestBean();
	// spouse for autowiring by type...
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
	builder.addConstructorArgValue("David Gavurin");

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("Mmm, I fancy a salad!", builder.getBeanDefinition());

	BeanWiringInfoResolver resolver = mock(BeanWiringInfoResolver.class);
	given(resolver.resolveWiringInfo(beanInstance)).willReturn(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false));

	BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
	configurer.setBeanFactory(factory);
	configurer.setBeanWiringInfoResolver(resolver);
	configurer.configureBean(beanInstance);
	assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName());
}
 
Example 2
private void parseNested(Element element, String eltType, ParserContext parserContext, BeanDefinitionBuilder builder, RedissonNamespaceParserSupport helper) {
    NodeList list = element.getElementsByTagNameNS(
            RedissonNamespaceParserSupport.REDISSON_NAMESPACE, eltType);
    if (list.getLength() == 1) {
        Element elt = (Element) list.item(0);
        if (StringUtils.hasText(referenceAttribute)) {
            helper.setAttribute(elt, referenceAttribute,
                    helper.getAttribute(element,
                            RedissonNamespaceParserSupport.ID_ATTRIBUTE));
            helper.setAttribute(elt, RedissonNamespaceParserSupport.REDISSON_REF_ATTRIBUTE,
                    helper.getAttribute(element,
                            RedissonNamespaceParserSupport.REDISSON_REF_ATTRIBUTE));
        }
        parserContext.getDelegate()
                .parseCustomElement(elt, builder.getRawBeanDefinition());
    }
}
 
Example 3
@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
private void configureRejectionPolicy(Element element, BeanDefinitionBuilder builder) {
	String rejectionPolicy = element.getAttribute("rejection-policy");
	if (!StringUtils.hasText(rejectionPolicy)) {
		return;
	}
	String prefix = "java.util.concurrent.ThreadPoolExecutor.";
	String policyClassName;
	if (rejectionPolicy.equals("ABORT")) {
		policyClassName = prefix + "AbortPolicy";
	}
	else if (rejectionPolicy.equals("CALLER_RUNS")) {
		policyClassName = prefix + "CallerRunsPolicy";
	}
	else if (rejectionPolicy.equals("DISCARD")) {
		policyClassName = prefix + "DiscardPolicy";
	}
	else if (rejectionPolicy.equals("DISCARD_OLDEST")) {
		policyClassName = prefix + "DiscardOldestPolicy";
	}
	else {
		policyClassName = rejectionPolicy;
	}
	builder.addPropertyValue("rejectedExecutionHandler", new RootBeanDefinition(policyClassName));
}
 
Example 5
@Test
public void testWithThreeRequiredPropertiesOmitted() {
	try {
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.addPropertyValue("name", "Rob Harrop")
			.getBeanDefinition();
		factory.registerBeanDefinition("testBean", beanDef);
		factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
		factory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		String message = ex.getCause().getMessage();
		assertTrue(message.contains("Properties"));
		assertTrue(message.contains("age"));
		assertTrue(message.contains("favouriteColour"));
		assertTrue(message.contains("jobTitle"));
		assertTrue(message.contains("testBean"));
	}
}
 
Example 6
Source Project: redisson   Source File: RedissonNamespaceParserSupport.java    License: Apache License 2.0 6 votes vote down vote up
private BeanDefinitionBuilder preInvoke(Element element, Object obj, String method, Object[] args, ParserContext parserContext, boolean factory) {
    Class<?> beanClass = BeanMethodInvoker.class;
    if (factory) {
        beanClass = MethodInvokingFactoryBean.class;
    }
    
    BeanDefinitionBuilder builder
            = createBeanDefinitionBuilder(element, parserContext, beanClass);
    if (obj instanceof Class) {
        builder.addPropertyValue("staticMethod",
                ((Class<?>) obj).getName() + "." + method);
    } else {
        builder.addPropertyValue("targetMethod", method);
    }
    builder.addPropertyValue("arguments", args);
    if (element != null) {
        parserContext.getDelegate().parseQualifierElements(element,
                builder.getRawBeanDefinition());
    }
    return builder;
}
 
Example 7
Source Project: spring-analysis-note   Source File: CacheAdviceParser.java    License: MIT License 6 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	builder.addPropertyReference("cacheManager", CacheNamespaceHandler.extractCacheManager(element));
	CacheNamespaceHandler.parseKeyGenerator(element, builder.getBeanDefinition());

	List<Element> cacheDefs = DomUtils.getChildElementsByTagName(element, DEFS_ELEMENT);
	if (!cacheDefs.isEmpty()) {
		// Using attributes source.
		List<RootBeanDefinition> attributeSourceDefinitions = parseDefinitionsSources(cacheDefs, parserContext);
		builder.addPropertyValue("cacheOperationSources", attributeSourceDefinitions);
	}
	else {
		// Assume annotations source.
		builder.addPropertyValue("cacheOperationSources",
				new RootBeanDefinition("org.springframework.cache.annotation.AnnotationCacheOperationSource"));
	}
}
 
Example 8
@Test
public void testExplicitScopeInheritanceForChildBeanDefinitions() {
	String theChildScope = "bonanza!";

	RootBeanDefinition parent = new RootBeanDefinition();
	parent.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);

	AbstractBeanDefinition child = BeanDefinitionBuilder.childBeanDefinition("parent").getBeanDefinition();
	child.setBeanClass(TestBean.class);
	child.setScope(theChildScope);

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("parent", parent);
	factory.registerBeanDefinition("child", child);

	AbstractBeanDefinition def = (AbstractBeanDefinition) factory.getBeanDefinition("child");
	assertEquals("Child 'scope' not overriding parent scope (it must).", theChildScope, def.getScope());
}
 
Example 9
@Test
public void testPrototypeScriptedBean() throws Exception {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.registerBeanDefinition("messenger", BeanDefinitionBuilder.rootBeanDefinition(StubMessenger.class).getBeanDefinition());

	BeanDefinitionBuilder scriptedBeanBuilder = BeanDefinitionBuilder.rootBeanDefinition(GroovyScriptFactory.class);
	scriptedBeanBuilder.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	scriptedBeanBuilder.addConstructorArgValue(DELEGATING_SCRIPT);
	scriptedBeanBuilder.addPropertyReference("messenger", "messenger");

	final String BEAN_WITH_DEPENDENCY_NAME = "needsMessenger";
	ctx.registerBeanDefinition(BEAN_WITH_DEPENDENCY_NAME, scriptedBeanBuilder.getBeanDefinition());
	ctx.registerBeanDefinition("scriptProcessor", createScriptFactoryPostProcessor(true));
	ctx.refresh();

	Messenger messenger1 = (Messenger) ctx.getBean(BEAN_WITH_DEPENDENCY_NAME);
	Messenger messenger2 = (Messenger) ctx.getBean(BEAN_WITH_DEPENDENCY_NAME);
	assertNotSame(messenger1, messenger2);
}
 
Example 10
Source Project: redisson   Source File: RedissonDefinitionParser.java    License: 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 11
Source Project: spring-cloud-connectors   Source File: CloudScanHelper.java    License: Apache License 2.0 6 votes vote down vote up
private void registerServiceBean(BeanDefinitionRegistry registry, ServiceInfo serviceInfo) {
	try {
		GenericCloudServiceConnectorFactory serviceFactory =
				new GenericCloudServiceConnectorFactory(serviceInfo.getId(), null);
		serviceFactory.setBeanFactory((BeanFactory) registry);
		serviceFactory.afterPropertiesSet();
		BeanDefinitionBuilder definitionBuilder =
				BeanDefinitionBuilder.genericBeanDefinition(ScannedServiceWrapper.class);
		definitionBuilder.addConstructorArgValue(serviceFactory);
		definitionBuilder.getRawBeanDefinition().setAttribute(
								  "factoryBeanObjectType", serviceFactory.getObjectType());
		registry.registerBeanDefinition(serviceInfo.getId(), definitionBuilder.getBeanDefinition());
	} catch (Exception ex) {
		logger.fine("Unable to create service for " + serviceInfo.getId() + " during service scanning. Skipping.");
	}
}
 
Example 12
Source Project: spring-analysis-note   Source File: MBeanExporterTests.java    License: MIT License 6 votes vote down vote up
@Test  // SPR-3302
public void testBeanNameCanBeUsedInNotificationListenersMap() throws Exception {
	String beanName = "charlesDexterWard";
	BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class);

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition(beanName, testBean.getBeanDefinition());
	factory.preInstantiateSingletons();
	Object testBeanInstance = factory.getBean(beanName);

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(getServer());
	Map<String, Object> beansToExport = new HashMap<>();
	beansToExport.put("test:what=ever", testBeanInstance);
	exporter.setBeans(beansToExport);
	exporter.setBeanFactory(factory);
	StubNotificationListener listener = new StubNotificationListener();
	exporter.setNotificationListenerMappings(Collections.singletonMap(beanName, listener));

	start(exporter);
}
 
Example 13
Source Project: idworker   Source File: GeneratorBeanDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    Class<?> generatorClass = null;
    if (ConfigConstants.SNOWFLAKE.equals(generatorType)) {
        generatorClass = SnowflakeGenerator.class;
    } else if (ConfigConstants.COMPRESS_UUID.equals(generatorType)) {
        generatorClass = CompressUUIDGenerator.class;
    } else {
        throw new IllegalArgumentException("unknown registryType");
    }
    BeanDefinitionBuilder result = BeanDefinitionBuilder.rootBeanDefinition(generatorClass);
    // snowflake 生成策略
    if (generatorClass.isAssignableFrom(SnowflakeGenerator.class)) {
        result.addConstructorArgValue(
                GeneratorRegisteryBuilder.buildWorkerNodeRegisterBeanDefinition(element, parserContext));
        // 去掉低并发模式配置解析
        // result.addPropertyValue(PropertyConstants.LOW_CONCURRENCY,
        // getAttributeValue(element,
        // GeneratorBeanDefinitionTag.LOW_CONCURRENCY));
        result.setInitMethodName("init");
    }
    return result.getBeanDefinition();
}
 
Example 14
@Test
public void testWithRequiredPropertyOmitted() {
	try {
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.addPropertyValue("name", "Rob Harrop")
			.addPropertyValue("favouriteColour", "Blue")
			.addPropertyValue("jobTitle", "Grand Poobah")
			.getBeanDefinition();
		factory.registerBeanDefinition("testBean", beanDef);
		factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
		factory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		String message = ex.getCause().getMessage();
		assertTrue(message.contains("Property"));
		assertTrue(message.contains("age"));
		assertTrue(message.contains("testBean"));
	}
}
 
Example 15
Source Project: spring4-understanding   Source File: CacheAdviceParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	builder.addPropertyReference("cacheManager", CacheNamespaceHandler.extractCacheManager(element));
	CacheNamespaceHandler.parseKeyGenerator(element, builder.getBeanDefinition());

	List<Element> cacheDefs = DomUtils.getChildElementsByTagName(element, DEFS_ELEMENT);
	if (cacheDefs.size() >= 1) {
		// Using attributes source.
		List<RootBeanDefinition> attributeSourceDefinitions = parseDefinitionsSources(cacheDefs, parserContext);
		builder.addPropertyValue("cacheOperationSources", attributeSourceDefinitions);
	}
	else {
		// Assume annotations source.
		builder.addPropertyValue("cacheOperationSources",
				new RootBeanDefinition("org.springframework.cache.annotation.AnnotationCacheOperationSource"));
	}
}
 
Example 16
Source Project: rice   Source File: CustomSchemaParser.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Parses a bean based on the namespace of the bean.
 *
 * @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 parseBean(Element tag, BeanDefinitionBuilder parent, ParserContext parserContext) {
    if (tag.getNamespaceURI().compareTo("http://www.springframework.org/schema/beans") == 0 || tag.getLocalName()
            .equals("bean")) {
        return parseSpringBean(tag, parserContext);
    } else {
        return parseCustomBean(tag, parent, parserContext);
    }
}
 
Example 17
static AbstractBeanDefinition getBeanDefinitionByElement(final Element element) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(StrategyConfig.class);
    factory.addPropertyValue("shardingColumns", element.getAttribute(ShardingJdbcStrategyBeanDefinitionParserTag.SHARDING_COLUMNS_ATTRIBUTE));
    factory.addPropertyValue("algorithmClassName", element.getAttribute(ShardingJdbcStrategyBeanDefinitionParserTag.ALGORITHM_CLASS_ATTRIBUTE));
    factory.addPropertyValue("algorithmExpression", element.getAttribute(ShardingJdbcStrategyBeanDefinitionParserTag.ALGORITHM_EXPRESSION_ATTRIBUTE));
    return factory.getBeanDefinition();
}
 
Example 18
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder result = BeanDefinitionBuilder.rootBeanDefinition(ZookeeperRegistryCenter.class);
    result.addConstructorArgValue(buildZookeeperConfigurationBeanDefinition(element));
    result.setInitMethodName("init");
    return result.getBeanDefinition();
}
 
Example 19
Source Project: jeesuite-libs   Source File: DruidDataSourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static BeanDefinitionBuilder builder(Properties props){
	
	BeanDefinitionBuilder beanDefinitionBuilder =  BeanDefinitionBuilder.genericBeanDefinition(DruidDataSource.class);
	
	String cryptKey = props.getProperty("config.cryptKey");
	if(props.containsKey("name"))beanDefinitionBuilder.addPropertyValue("name", props.getProperty("name"));
   	beanDefinitionBuilder.addPropertyValue("driverClassName", props.getProperty("driverClassName"));
   	beanDefinitionBuilder.addPropertyValue("url", props.getProperty("url"));
   	beanDefinitionBuilder.addPropertyValue("username", props.getProperty("username"));
   	
   	String password = props.getProperty("password");
   	if(StringUtils.isNotBlank(cryptKey) && !ResourceUtils.NULL_VALUE_PLACEHOLDER.equals(cryptKey)){
   		try {
   			password = SimpleCryptUtils.decrypt(cryptKey, password);
		} catch (Exception e) {
			System.err.println(">> find config[db.config.cryptKey],but decrypt error ,use orign password");
		}
   	}
   	beanDefinitionBuilder.addPropertyValue("password", password);
   	beanDefinitionBuilder.addPropertyValue("testWhileIdle", Boolean.parseBoolean(props.getProperty("testWhileIdle","true")));
   	beanDefinitionBuilder.addPropertyValue("validationQuery", props.getProperty("validationQuery","SELECT 'x'"));
   	beanDefinitionBuilder.addPropertyValue("maxActive", Integer.parseInt(props.getProperty("maxActive","10")));
   	beanDefinitionBuilder.addPropertyValue("initialSize", Integer.parseInt(props.getProperty("initialSize","1")));
   	beanDefinitionBuilder.addPropertyValue("minIdle", Integer.parseInt(props.getProperty("minIdle","1")));
   	beanDefinitionBuilder.addPropertyValue("maxWait", Long.parseLong(props.getProperty("maxWait","10000")));
   	beanDefinitionBuilder.addPropertyValue("minEvictableIdleTimeMillis", Long.parseLong(props.getProperty("minEvictableIdleTimeMillis","60000")));
   	beanDefinitionBuilder.addPropertyValue("timeBetweenEvictionRunsMillis", Long.parseLong(props.getProperty("timeBetweenEvictionRunsMillis","60000")));
   	beanDefinitionBuilder.addPropertyValue("testOnBorrow", Boolean.parseBoolean(props.getProperty("testOnBorrow","true")));
   	beanDefinitionBuilder.addPropertyValue("testOnReturn", Boolean.parseBoolean(props.getProperty("testOnReturn","false")));

   	return beanDefinitionBuilder;
       
}
 
Example 20
@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 21
Source Project: spring-integration-aws   Source File: SnsParserUtils.java    License: MIT License 5 votes vote down vote up
public static void registerExecutorProxy(Element element,
		String snsExecutorBeanName, ParserContext parserContext) {

	if (element.hasAttribute("sns-executor-proxy")) {
		String snsProxyBeanName = element
				.getAttribute("sns-executor-proxy");
		BeanDefinitionBuilder snsExecutorProxyBuilder = BeanDefinitionBuilder
				.genericBeanDefinition(SnsExecutorProxy.class);
		snsExecutorProxyBuilder
				.addConstructorArgReference(snsExecutorBeanName);
		parserContext.registerBeanComponent(new BeanComponentDefinition(
				snsExecutorProxyBuilder.getBeanDefinition(),
				snsProxyBeanName));
	}
}
 
Example 22
protected BeanDefinitionBuilder parseHandler(Element element,
		ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
			"com.github.moonkev.spring.integration.zmq.ZmqOutboundGateway");
	
	builder.addPropertyValue("address", element.getAttribute("address"));
	builder.addPropertyValue("socketType", element.getAttribute("socket-type"));
	IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "bind");
	IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "send-timeout", "socketSendTimeout");
	IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "receive-timeout", "socketReceiveTimeout");
	IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "linger");
	IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel");
	IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "context-manager");
	
	if ("".equals(element.getAttribute("request-converter"))) {
		builder.addPropertyValue("requestConverter", new MapToJsonByteArrayConverter());
	} else {
		builder.addPropertyReference("request-converter", element.getAttribute("requestConverter"));
	}
	
	if ("".equals(element.getAttribute("reply-converter"))) {
		builder.addPropertyValue("replyConverter", new JsonByteArrayToMapConverter());
	} else {
		builder.addPropertyReference("reply-converter", element.getAttribute("replyConverter"));
	}

	return builder;		
}
 
Example 23
private void configureRejectionPolicy(Element element, BeanDefinitionBuilder builder) {
	String rejectionPolicy = element.getAttribute("rejection-policy");
	if (!StringUtils.hasText(rejectionPolicy)) {
		return;
	}
	String prefix = "java.util.concurrent.ThreadPoolExecutor.";
	if (builder.getRawBeanDefinition().getBeanClassName().contains("backport")) {
		prefix = "edu.emory.mathcs.backport." + prefix;
	}
	String policyClassName;
	if (rejectionPolicy.equals("ABORT")) {
		policyClassName = prefix + "AbortPolicy";
	}
	else if (rejectionPolicy.equals("CALLER_RUNS")) {
		policyClassName = prefix + "CallerRunsPolicy";
	}
	else if (rejectionPolicy.equals("DISCARD")) {
		policyClassName = prefix + "DiscardPolicy";
	}
	else if (rejectionPolicy.equals("DISCARD_OLDEST")) {
		policyClassName = prefix + "DiscardOldestPolicy";
	}
	else {
		policyClassName = rejectionPolicy;
	}
	builder.addPropertyValue("rejectedExecutionHandler", new RootBeanDefinition(policyClassName));
}
 
Example 24
/**
 * 设置缓存处理器
 * @param mangoBuilder
 */

private void configCacheHandler(BeanDefinitionBuilder mangoBuilder){
    String cacheHandlerClassPath = config.getCacheHandler();
    if(!Strings.isEmpty(cacheHandlerClassPath)) {
        try {
            Class<? extends CacheHandler> cachHandlerClz = (Class<? extends CacheHandler>) Class.forName(cacheHandlerClassPath);
            CacheHandler cacheHandler = Reflection.instantiateClass(cachHandlerClz);
            mangoBuilder.addPropertyValue("cacheHandler", cacheHandler);
        } catch (Throwable e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
 
Example 25
@Bean
public static BeanDefinitionRegistryPostProcessor removeUnwantedAutomaticFilterRegistration() {
    return new BeanDefinitionRegistryPostProcessor() {
        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) throws BeansException {
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) bf;
            Set<String> filtersToDisable = ImmutableSet.of("samlEntryPoint", "samlFilter", "samlIDPDiscovery", "metadataDisplayFilter",
                    "samlWebSSOHoKProcessingFilter", "samlWebSSOProcessingFilter",
                    "samlLogoutProcessingFilter", "samlLogoutFilter", "metadataGeneratorFilter");
            Arrays.stream(beanFactory.getBeanNamesForType(javax.servlet.Filter.class))
                    .filter(filtersToDisable::contains)
                    .forEach(name -> {
                        BeanDefinition definition = BeanDefinitionBuilder
                                .genericBeanDefinition(FilterRegistrationBean.class)
                                .setScope(BeanDefinition.SCOPE_SINGLETON)
                                .addConstructorArgReference(name)
                                .addConstructorArgValue(new ServletRegistrationBean[]{})
                                .addPropertyValue("enabled", false)
                                .getBeanDefinition();
                        beanFactory.registerBeanDefinition(name + "FilterRegistrationBean", definition);
                    });
        }
    };
}
 
Example 26
Source Project: spring-cloud-aws   Source File: QueueMessageHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private AbstractBeanDefinition getQueueMessageHandlerBeanDefinition() {
	BeanDefinitionBuilder queueMessageHandlerBeanDefinitionBuilder = BeanDefinitionBuilder
			.rootBeanDefinition(QueueMessageHandler.class);
	ManagedList<HandlerMethodReturnValueHandler> returnValueHandlers = new ManagedList<>(
			1);
	returnValueHandlers
			.add(new SendToHandlerMethodReturnValueHandler(this.messageTemplate));
	queueMessageHandlerBeanDefinitionBuilder.addPropertyValue("returnValueHandlers",
			returnValueHandlers);
	return queueMessageHandlerBeanDefinitionBuilder.getBeanDefinition();
}
 
Example 27
@Override
protected void doParse(final Element element, final BeanDefinitionBuilder builder) {
    
    String location = element.getAttribute("location");
    if (StringUtils.hasLength(location)) {
        String[] locations = StringUtils.commaDelimitedListToStringArray(location);
        builder.addPropertyValue("locations", locations);
    }

    String propertiesRef = element.getAttribute("properties-ref");
    if (StringUtils.hasLength(propertiesRef)) {
        builder.addPropertyReference("properties", propertiesRef);
    }

    String fileEncoding = element.getAttribute("file-encoding");
    if (StringUtils.hasLength(fileEncoding)) {
        builder.addPropertyReference("fileEncoding", fileEncoding);
    }

    String order = element.getAttribute("order");
    if (StringUtils.hasLength(order)) {
        builder.addPropertyValue("order", Integer.valueOf(order));
    }

    builder.addPropertyValue("ignoreResourceNotFound",
            Boolean.valueOf(element.getAttribute("ignore-resource-not-found")));

    builder.addPropertyValue("localOverride",
            Boolean.valueOf(element.getAttribute("local-override")));

    builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
}
 
Example 28
protected final AbstractBeanDefinition createDataSource(MybatisNodeProperties druidNodeConfig,
		DruidProperties defaultConfig, String dataSourceName) {
	Assert.notNull(druidNodeConfig, String
			.format("DynamicDataSource 未初始化 ,dataSourceName=%s,失败原因: 配置参数为空,你的配置可能存在问题!", dataSourceName + ""));
	BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(DynamicDataSource.class);
	definitionBuilder.addConstructorArgValue(druidNodeConfig);
	definitionBuilder.addConstructorArgValue(defaultConfig);
	definitionBuilder.addConstructorArgValue(dataSourceName);
	definitionBuilder.setInitMethodName("init");
	definitionBuilder.setDestroyMethodName("close");
	return definitionBuilder.getRawBeanDefinition();
}
 
Example 29
Source Project: greenmail   Source File: GreenMailBeanDefinitionParser.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void doParse(final Element element, final BeanDefinitionBuilder builder) {
    builder.addPropertyValue("hostname", extractHostname(element));
    builder.addPropertyValue("portOffset", extractPortOffset(element));
    builder.addPropertyValue("serverStartupTimeout", extractServerStartupTimeout(element));
}
 
Example 30
Source Project: zxl   Source File: MqBeanParser.java    License: Apache License 2.0 5 votes vote down vote up
protected void doParseOther(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	if (element.hasAttribute(QUEUE_DURABLE_NAME)) {
		builder.addPropertyValue("queueDurable", Boolean.valueOf(element.getAttribute(QUEUE_DURABLE_NAME)));
	}
	if (element.hasAttribute(QUEUE_EXCLUSIVE_NAME)) {
		builder.addPropertyValue("queueExclusive", Boolean.valueOf(element.getAttribute(QUEUE_EXCLUSIVE_NAME)));
	}
	if (element.hasAttribute(QUEUE_AUTO_DELETE_NAME)) {
		builder.addPropertyValue("queueAutoDelete", Boolean.valueOf(element.getAttribute(QUEUE_AUTO_DELETE_NAME)));
	}
}