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

The following examples show how to use org.springframework.beans.factory.config.RuntimeBeanReference. 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: GroovyBeanDefinitionReader.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Checks whether there are any {@link RuntimeBeanReference RuntimeBeanReferences}
 * inside the {@link Map} and converts it to a {@link ManagedMap} if necessary.
 * @param map the original Map
 * @return either the original map or a managed copy of it
 */
private Object manageMapIfNecessary(Map<?, ?> map) {
	boolean containsRuntimeRefs = false;
	for (Object element : map.values()) {
		if (element instanceof RuntimeBeanReference) {
			containsRuntimeRefs = true;
			break;
		}
	}
	if (containsRuntimeRefs) {
		Map<Object, Object> managedMap = new ManagedMap<>();
		managedMap.putAll(map);
		return managedMap;
	}
	return map;
}
 
Example #2
Source File: DubboBeanDefinitionParser.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
private static void parseNested(Element element, ParserContext parserContext, Class<?> beanClass, boolean required, String tag, String property, String ref, BeanDefinition beanDefinition) {
    NodeList nodeList = element.getChildNodes();
    if (nodeList != null && nodeList.getLength() > 0) {
        boolean first = true;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                if (tag.equals(node.getNodeName())
                        || tag.equals(node.getLocalName())) {
                    if (first) {
                        first = false;
                        String isDefault = element.getAttribute("default");
                        if (isDefault == null || isDefault.length() == 0) {
                            beanDefinition.getPropertyValues().addPropertyValue("default", "false");
                        }
                    }
                    BeanDefinition subDefinition = parse((Element) node, parserContext, beanClass, required);
                    if (subDefinition != null && ref != null && ref.length() > 0) {
                        subDefinition.getPropertyValues().addPropertyValue(property, new RuntimeBeanReference(ref));
                    }
                }
            }
        }
    }
}
 
Example #3
Source File: AutowireWithExclusionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void byTypeAutowireWithPrimaryInParentFactory() throws Exception {
	CountingFactory.reset();
	DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
	parent.getBeanDefinition("props1").setPrimary(true);
	parent.preInstantiateSingletons();
	DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
	RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class);
	robDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
	child.registerBeanDefinition("rob2", robDef);
	RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
	propsDef.getPropertyValues().add("properties", "name=props3");
	child.registerBeanDefinition("props3", propsDef);
	TestBean rob = (TestBean) child.getBean("rob2");
	assertEquals("props1", rob.getSomeProperties().getProperty("name"));
	assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
 
Example #4
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 6 votes vote down vote up
/**
 * @param referenceFactory
 * @param from
 * @param to
 * @param reload
 * @param transition
 * @param transitionId
 * @param reg
 * @param actionRef
 */
private void registerTransition(ReferenceFactory referenceFactory,
		String from, String to, boolean reload, Transition transition,
		String transitionId, BeanDefinitionRegistry reg,
		RuntimeBeanReference actionRef) {
	// Build the Transition Bean
	//
	BeanDefinition transitionBean = BeanDefinitionBuilder
			.genericBeanDefinition(TransitionImpl.class)
			.getBeanDefinition();

	String fromId = referenceFactory.getStateId(from);
	String toId = referenceFactory.getStateId(to);
	Pair<String, String> providerEvent = parseEvent(transition.event());

	ConstructorArgumentValues args = transitionBean.getConstructorArgumentValues();
	args.addIndexedArgumentValue(0, new RuntimeBeanReference(fromId));
	args.addIndexedArgumentValue(1, new RuntimeBeanReference(toId));
	args.addIndexedArgumentValue(2, providerEvent.getRight());
	args.addIndexedArgumentValue(3, actionRef);
	args.addIndexedArgumentValue(4,
			(transition.from().equals(Transition.ANY_STATE) &&
			 transition.to().equals(Transition.ANY_STATE)));
	args.addIndexedArgumentValue(5, reload);
	reg.registerBeanDefinition(transitionId, transitionBean);
}
 
Example #5
Source File: DubboBeanDefinitionParser.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition) {
    if (nodeList != null && nodeList.getLength() > 0) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                if ("property".equals(node.getNodeName())
                        || "property".equals(node.getLocalName())) {
                    String name = ((Element) node).getAttribute("name");
                    if (name != null && name.length() > 0) {
                        String value = ((Element) node).getAttribute("value");
                        String ref = ((Element) node).getAttribute("ref");
                        if (value != null && value.length() > 0) {
                            beanDefinition.getPropertyValues().addPropertyValue(name, value);
                        } else if (ref != null && ref.length() > 0) {
                            beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref));
                        } else {
                            throw new UnsupportedOperationException("Unsupported <property name=\"" + name + "\"> sub tag, Only supported <property name=\"" + name + "\" ref=\"...\" /> or <property name=\"" + name + "\" value=\"...\" />");
                        }
                    }
                }
            }
        }
    }
}
 
Example #6
Source File: HandlersBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void addMapping(Element element, ManagedMap<String, Object> urlMap, ParserContext context) {
	String pathAttribute = element.getAttribute("path");
	List<String> mappings = Arrays.asList(StringUtils.tokenizeToStringArray(pathAttribute, ","));
	RuntimeBeanReference handlerReference = new RuntimeBeanReference(element.getAttribute("handler"));

	ConstructorArgumentValues cavs = new ConstructorArgumentValues();
	cavs.addIndexedArgumentValue(0, handlerReference);
	if (this.handshakeHandlerReference != null) {
		cavs.addIndexedArgumentValue(1, this.handshakeHandlerReference);
	}
	RootBeanDefinition requestHandlerDef = new RootBeanDefinition(WebSocketHttpRequestHandler.class, cavs, null);
	requestHandlerDef.setSource(context.extractSource(element));
	requestHandlerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	requestHandlerDef.getPropertyValues().add("handshakeInterceptors", this.interceptorsList);
	String requestHandlerName = context.getReaderContext().registerWithGeneratedName(requestHandlerDef);
	RuntimeBeanReference requestHandlerRef = new RuntimeBeanReference(requestHandlerName);

	for (String mapping : mappings) {
		urlMap.put(mapping, requestHandlerRef);
	}
}
 
Example #7
Source File: GroovyBeanDefinitionReader.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether there are any {@link RuntimeBeanReference}s inside the Map
 * and converts it to a ManagedMap if necessary.
 * @param map the original Map
 * @return either the original map or a managed copy of it
 */
private Object manageMapIfNecessary(Map<?, ?> map) {
	boolean containsRuntimeRefs = false;
	for (Object element : map.values()) {
		if (element instanceof RuntimeBeanReference) {
			containsRuntimeRefs = true;
			break;
		}
	}
	if (containsRuntimeRefs) {
		Map<Object, Object> managedMap = new ManagedMap<Object, Object>();
		managedMap.putAll(map);
		return managedMap;
	}
	return map;
}
 
Example #8
Source File: MessageBrokerBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private RuntimeBeanReference registerUserDestHandler(Element brokerElem,
		RuntimeBeanReference userRegistry, RuntimeBeanReference inChannel,
		RuntimeBeanReference brokerChannel, ParserContext context, Object source) {

	Object userDestResolver = registerUserDestResolver(brokerElem, userRegistry, context, source);

	RootBeanDefinition beanDef = new RootBeanDefinition(UserDestinationMessageHandler.class);
	beanDef.getConstructorArgumentValues().addIndexedArgumentValue(0, inChannel);
	beanDef.getConstructorArgumentValues().addIndexedArgumentValue(1, brokerChannel);
	beanDef.getConstructorArgumentValues().addIndexedArgumentValue(2, userDestResolver);

	Element relayElement = DomUtils.getChildElementByTagName(brokerElem, "stomp-broker-relay");
	if (relayElement != null && relayElement.hasAttribute("user-destination-broadcast")) {
		String destination = relayElement.getAttribute("user-destination-broadcast");
		beanDef.getPropertyValues().add("broadcastDestination", destination);
	}

	String beanName = registerBeanDef(beanDef, context, source);
	return new RuntimeBeanReference(beanName);
}
 
Example #9
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomEditorWithBeanReference() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
		@Override
		public void registerCustomEditors(PropertyEditorRegistry registry) {
			NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
			registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
		}
	});
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", new RuntimeBeanReference("myFloat"));
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	lbf.registerSingleton("myFloat", "1,1");
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
Example #10
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomTypeConverterWithBeanReference() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
	lbf.setTypeConverter(new CustomTypeConverter(nf));
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", new RuntimeBeanReference("myFloat"));
	ConstructorArgumentValues cav = new ConstructorArgumentValues();
	cav.addIndexedArgumentValue(0, "myName");
	cav.addIndexedArgumentValue(1, "myAge");
	lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, cav, pvs));
	lbf.registerSingleton("myFloat", "1,1");
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertEquals("myName", testBean.getName());
	assertEquals(5, testBean.getAge());
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
Example #11
Source File: AnnotationDrivenBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private RuntimeBeanReference getValidator(Element element, @Nullable Object source, ParserContext context) {
	if (element.hasAttribute("validator")) {
		return new RuntimeBeanReference(element.getAttribute("validator"));
	}
	else if (javaxValidationPresent) {
		RootBeanDefinition validatorDef = new RootBeanDefinition(
				"org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
		validatorDef.setSource(source);
		validatorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		String validatorName = context.getReaderContext().registerWithGeneratedName(validatorDef);
		context.registerComponent(new BeanComponentDefinition(validatorDef, validatorName));
		return new RuntimeBeanReference(validatorName);
	}
	else {
		return null;
	}
}
 
Example #12
Source File: MessageBrokerBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
private ManagedMap<String, Object> registerHandlerMapping(
		Element element, ParserContext context, @Nullable Object source) {

	RootBeanDefinition handlerMappingDef = new RootBeanDefinition(WebSocketHandlerMapping.class);

	String orderAttribute = element.getAttribute("order");
	int order = orderAttribute.isEmpty() ? DEFAULT_MAPPING_ORDER : Integer.valueOf(orderAttribute);
	handlerMappingDef.getPropertyValues().add("order", order);

	String pathHelper = element.getAttribute("path-helper");
	if (StringUtils.hasText(pathHelper)) {
		handlerMappingDef.getPropertyValues().add("urlPathHelper", new RuntimeBeanReference(pathHelper));
	}

	ManagedMap<String, Object> urlMap = new ManagedMap<>();
	urlMap.setSource(source);
	handlerMappingDef.getPropertyValues().add("urlMap", urlMap);

	registerBeanDef(handlerMappingDef, context, source);
	return urlMap;
}
 
Example #13
Source File: AutowireWithExclusionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void byTypeAutowireWithPrimaryInParentFactory() throws Exception {
	CountingFactory.reset();
	DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
	parent.getBeanDefinition("props1").setPrimary(true);
	parent.preInstantiateSingletons();
	DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
	RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class);
	robDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
	child.registerBeanDefinition("rob2", robDef);
	RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
	propsDef.getPropertyValues().add("properties", "name=props3");
	child.registerBeanDefinition("props3", propsDef);
	TestBean rob = (TestBean) child.getBean("rob2");
	assertEquals("props1", rob.getSomeProperties().getProperty("name"));
	assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
 
Example #14
Source File: AnnotationProcessorPerformanceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrototypeCreationWithOverriddenResourcePropertiesIsFastEnough() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx);
	ctx.refresh();

	RootBeanDefinition rbd = new RootBeanDefinition(ResourceAnnotatedTestBean.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.getPropertyValues().add("spouse", new RuntimeBeanReference("spouse"));
	ctx.registerBeanDefinition("test", rbd);
	ctx.registerBeanDefinition("spouse", new RootBeanDefinition(TestBean.class));
	TestBean spouse = (TestBean) ctx.getBean("spouse");
	StopWatch sw = new StopWatch();
	sw.start("prototype");
	for (int i = 0; i < 100000; i++) {
		TestBean tb = (TestBean) ctx.getBean("test");
		assertSame(spouse, tb.getSpouse());
	}
	sw.stop();
	assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000);
}
 
Example #15
Source File: GroovyBeanDefinitionReader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Checks whether there are any {@link RuntimeBeanReference RuntimeBeanReferences}
 * inside the {@link List} and converts it to a {@link ManagedList} if necessary.
 * @param list the original List
 * @return either the original list or a managed copy of it
 */
private Object manageListIfNecessary(List<?> list) {
	boolean containsRuntimeRefs = false;
	for (Object element : list) {
		if (element instanceof RuntimeBeanReference) {
			containsRuntimeRefs = true;
			break;
		}
	}
	if (containsRuntimeRefs) {
		List<Object> managedList = new ManagedList<>();
		managedList.addAll(list);
		return managedList;
	}
	return list;
}
 
Example #16
Source File: AutowireWithExclusionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void byTypeAutowireWithPrimaryInParentFactory() throws Exception {
	CountingFactory.reset();
	DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
	parent.getBeanDefinition("props1").setPrimary(true);
	parent.preInstantiateSingletons();
	DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
	RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class);
	robDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
	child.registerBeanDefinition("rob2", robDef);
	RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
	propsDef.getPropertyValues().add("properties", "name=props3");
	child.registerBeanDefinition("props3", propsDef);
	TestBean rob = (TestBean) child.getBean("rob2");
	assertEquals("props1", rob.getSomeProperties().getProperty("name"));
	assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
 
Example #17
Source File: GroovyBeanDefinitionWrapper.java    From java-technology-stack with MIT License 6 votes vote down vote up
public void setParent(Object obj) {
	if (obj == null) {
		throw new IllegalArgumentException("Parent bean cannot be set to a null runtime bean reference!");
	}
	if (obj instanceof String) {
		this.parentName = (String) obj;
	}
	else if (obj instanceof RuntimeBeanReference) {
		this.parentName = ((RuntimeBeanReference) obj).getBeanName();
	}
	else if (obj instanceof GroovyBeanDefinitionWrapper) {
		this.parentName = ((GroovyBeanDefinitionWrapper) obj).getBeanName();
	}
	getBeanDefinition().setParentName(this.parentName);
	getBeanDefinition().setAbstract(false);
}
 
Example #18
Source File: HandlersBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void addMapping(Element element, ManagedMap<String, Object> urlMap, ParserContext context) {
	String pathAttribute = element.getAttribute("path");
	String[] mappings = StringUtils.tokenizeToStringArray(pathAttribute, ",");
	RuntimeBeanReference handlerReference = new RuntimeBeanReference(element.getAttribute("handler"));

	ConstructorArgumentValues cargs = new ConstructorArgumentValues();
	cargs.addIndexedArgumentValue(0, handlerReference);
	cargs.addIndexedArgumentValue(1, this.handshakeHandlerReference);
	RootBeanDefinition requestHandlerDef = new RootBeanDefinition(WebSocketHttpRequestHandler.class, cargs, null);
	requestHandlerDef.setSource(context.extractSource(element));
	requestHandlerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	requestHandlerDef.getPropertyValues().add("handshakeInterceptors", this.interceptorsList);
	String requestHandlerName = context.getReaderContext().registerWithGeneratedName(requestHandlerDef);
	RuntimeBeanReference requestHandlerRef = new RuntimeBeanReference(requestHandlerName);

	for (String mapping : mappings) {
		urlMap.put(mapping, requestHandlerRef);
	}
}
 
Example #19
Source File: MessageBrokerBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void registerWebSocketMessageBrokerStats(RootBeanDefinition broker, RuntimeBeanReference inChannel,
		RuntimeBeanReference outChannel, ParserContext context, @Nullable Object source) {

	RootBeanDefinition beanDef = new RootBeanDefinition(WebSocketMessageBrokerStats.class);

	RuntimeBeanReference webSocketHandler = new RuntimeBeanReference(WEB_SOCKET_HANDLER_BEAN_NAME);
	beanDef.getPropertyValues().add("subProtocolWebSocketHandler", webSocketHandler);

	if (StompBrokerRelayMessageHandler.class == broker.getBeanClass()) {
		beanDef.getPropertyValues().add("stompBrokerRelay", broker);
	}
	String name = inChannel.getBeanName() + "Executor";
	if (context.getRegistry().containsBeanDefinition(name)) {
		beanDef.getPropertyValues().add("inboundChannelExecutor", context.getRegistry().getBeanDefinition(name));
	}
	name = outChannel.getBeanName() + "Executor";
	if (context.getRegistry().containsBeanDefinition(name)) {
		beanDef.getPropertyValues().add("outboundChannelExecutor", context.getRegistry().getBeanDefinition(name));
	}
	Object scheduler = WebSocketNamespaceUtils.registerScheduler(SCHEDULER_BEAN_NAME, context, source);
	beanDef.getPropertyValues().add("sockJsTaskScheduler", scheduler);

	registerBeanDefByName("webSocketMessageBrokerStats", beanDef, context, source);
}
 
Example #20
Source File: DubboBeanDefinitionParser.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition) {
    if (nodeList != null && nodeList.getLength() > 0) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                if ("property".equals(node.getNodeName())
                        || "property".equals(node.getLocalName())) {
                    String name = ((Element) node).getAttribute("name");
                    if (name != null && name.length() > 0) {
                        String value = ((Element) node).getAttribute("value");
                        String ref = ((Element) node).getAttribute("ref");
                        if (value != null && value.length() > 0) {
                            beanDefinition.getPropertyValues().addPropertyValue(name, value);
                        } else if (ref != null && ref.length() > 0) {
                            beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref));
                        } else {
                            throw new UnsupportedOperationException("Unsupported <property name=\"" + name + "\"> sub tag, Only supported <property name=\"" + name + "\" ref=\"...\" /> or <property name=\"" + name + "\" value=\"...\" />");
                        }
                    }
                }
            }
        }
    }
}
 
Example #21
Source File: JupiterBeanDefinitionParser.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private static void addPropertyReferenceArray(
        RootBeanDefinition definition, Element element, String elementTypeName, String propertyName, boolean required) {
    String[] refArray = Strings.split(element.getAttribute(propertyName), ',');
    List<RuntimeBeanReference> refBeanList = Lists.newArrayListWithCapacity(refArray.length);
    for (String ref : refArray) {
        ref = ref.trim();
        if (required) {
            checkAttribute(propertyName, ref);
        }
        if (!Strings.isNullOrEmpty(ref)) {
            refBeanList.add(new RuntimeBeanReference(ref));
        }
    }

    if (!refBeanList.isEmpty()) {
        ManagedArray managedArray = new ManagedArray(elementTypeName, refBeanList.size());
        managedArray.addAll(refBeanList);
        definition.getPropertyValues().addPropertyValue(propertyName, managedArray);
    }
}
 
Example #22
Source File: MessageBrokerBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
private RuntimeBeanReference getValidator(
		Element messageBrokerElement, @Nullable Object source, ParserContext context) {

	if (messageBrokerElement.hasAttribute("validator")) {
		return new RuntimeBeanReference(messageBrokerElement.getAttribute("validator"));
	}
	else if (javaxValidationPresent) {
		RootBeanDefinition validatorDef = new RootBeanDefinition(
				"org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
		validatorDef.setSource(source);
		validatorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		String validatorName = context.getReaderContext().registerWithGeneratedName(validatorDef);
		context.registerComponent(new BeanComponentDefinition(validatorDef, validatorName));
		return new RuntimeBeanReference(validatorName);
	}
	else {
		return null;
	}
}
 
Example #23
Source File: BeanDefinitionWriterServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private XStream createStream() {
	XStream stream = new XStream();
	stream.registerConverter(new BeanDefinitionConverter(stream.getMapper()));
	stream.registerConverter(new BeanDefinitionHolderConverter(stream.getMapper()));
	stream.registerConverter(new TypedStringValueConverter());
	stream.registerConverter(new ManagedCollectionConverter(stream.getMapper()));
	stream.registerConverter(new ManagedMapConverter(stream.getMapper()));
	stream.registerConverter(new RuntimeBeanReferenceConverter());
	stream.alias("map", ManagedMap.class);
	stream.alias("list", ManagedList.class);
	stream.alias("set", ManagedSet.class);
	stream.alias("array", ManagedArray.class);
	stream.aliasType("bean", BeanDefinition.class);
	stream.alias("bean", BeanDefinitionHolder.class);
	stream.alias("ref", RuntimeBeanReference.class);
	return stream;
}
 
Example #24
Source File: AnnotationDrivenBeanDefinitionParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private RuntimeBeanReference getValidator(Element element, Object source, ParserContext parserContext) {
	if (element.hasAttribute("validator")) {
		return new RuntimeBeanReference(element.getAttribute("validator"));
	}
	else if (javaxValidationPresent) {
		RootBeanDefinition validatorDef = new RootBeanDefinition(
				"org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
		validatorDef.setSource(source);
		validatorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		String validatorName = parserContext.getReaderContext().registerWithGeneratedName(validatorDef);
		parserContext.registerComponent(new BeanComponentDefinition(validatorDef, validatorName));
		return new RuntimeBeanReference(validatorName);
	}
	else {
		return null;
	}
}
 
Example #25
Source File: AnnotationProcessorPerformanceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testPrototypeCreationWithOverriddenAutowiredPropertiesIsFastEnough() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx);
	ctx.refresh();

	RootBeanDefinition rbd = new RootBeanDefinition(AutowiredAnnotatedTestBean.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.getPropertyValues().add("spouse", new RuntimeBeanReference("spouse"));
	ctx.registerBeanDefinition("test", rbd);
	ctx.registerBeanDefinition("spouse", new RootBeanDefinition(TestBean.class));
	TestBean spouse = (TestBean) ctx.getBean("spouse");
	StopWatch sw = new StopWatch();
	sw.start("prototype");
	for (int i = 0; i < 100000; i++) {
		TestBean tb = (TestBean) ctx.getBean("test");
		assertSame(spouse, tb.getSpouse());
	}
	sw.stop();
	assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 6000);
}
 
Example #26
Source File: GroovyBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether there are any {@link RuntimeBeanReference}s inside the {@link List}
 * and converts it to a {@link ManagedList} if necessary.
 * @param list the original List
 * @return either the original list or a managed copy of it
 */
private Object manageListIfNecessary(List<?> list) {
	boolean containsRuntimeRefs = false;
	for (Object element : list) {
		if (element instanceof RuntimeBeanReference) {
			containsRuntimeRefs = true;
			break;
		}
	}
	if (containsRuntimeRefs) {
		List<Object> managedList = new ManagedList<Object>();
		managedList.addAll(list);
		return managedList;
	}
	return list;
}
 
Example #27
Source File: AbstractCacheManagerAndProviderFacadeParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses the given XML element containing the properties of the cache manager
 * to register in the given registry of bean definitions.
 * 
 * @param element
 *          the XML element to parse
 * @param registry
 *          the registry of bean definitions
 * 
 * @see AbstractCacheProviderFacadeParser#doParse(String, Element,
 *      BeanDefinitionRegistry)
 */
protected final void doParse(String cacheProviderFacadeId, Element element,
    BeanDefinitionRegistry registry) {
  String id = "cacheManager";
  Class clazz = getCacheManagerClass();
  RootBeanDefinition cacheManager = new RootBeanDefinition(clazz);
  MutablePropertyValues cacheManagerProperties = new MutablePropertyValues();
  cacheManager.setPropertyValues(cacheManagerProperties);

  PropertyValue configLocation = parseConfigLocationProperty(element);
  cacheManagerProperties.addPropertyValue(configLocation);
  registry.registerBeanDefinition(id, cacheManager);

  BeanDefinition cacheProviderFacade = registry
      .getBeanDefinition(cacheProviderFacadeId);
  cacheProviderFacade.getPropertyValues().addPropertyValue("cacheManager",
      new RuntimeBeanReference(id));
}
 
Example #28
Source File: CacheAnnotationParser.java    From jetcache with Apache License 2.0 5 votes vote down vote up
private synchronized void doParse(Element element, ParserContext parserContext) {
    String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute("base-package"), ",; \t\n");
    AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
    if (!parserContext.getRegistry().containsBeanDefinition(CacheAdvisor.CACHE_ADVISOR_BEAN_NAME)) {
        Object eleSource = parserContext.extractSource(element);

        RootBeanDefinition configMapDef = new RootBeanDefinition(ConfigMap.class);
        configMapDef.setSource(eleSource);
        configMapDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        String configMapName = parserContext.getReaderContext().registerWithGeneratedName(configMapDef);

        RootBeanDefinition interceptorDef = new RootBeanDefinition(JetCacheInterceptor.class);
        interceptorDef.setSource(eleSource);
        interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        interceptorDef.getPropertyValues().addPropertyValue(new PropertyValue("cacheConfigMap", new RuntimeBeanReference(configMapName)));
        String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);

        RootBeanDefinition advisorDef = new RootBeanDefinition(CacheAdvisor.class);
        advisorDef.setSource(eleSource);
        advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        advisorDef.getPropertyValues().addPropertyValue(new PropertyValue("adviceBeanName", interceptorName));
        advisorDef.getPropertyValues().addPropertyValue(new PropertyValue("cacheConfigMap", new RuntimeBeanReference(configMapName)));
        advisorDef.getPropertyValues().addPropertyValue(new PropertyValue("basePackages", basePackages));
        parserContext.getRegistry().registerBeanDefinition(CacheAdvisor.CACHE_ADVISOR_BEAN_NAME, advisorDef);

        CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(),
                eleSource);
        compositeDef.addNestedComponent(new BeanComponentDefinition(configMapDef, configMapName));
        compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName));
        compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, CacheAdvisor.CACHE_ADVISOR_BEAN_NAME));
        parserContext.registerComponent(compositeDef);
    }
}
 
Example #29
Source File: AnnotationDrivenBeanDefinitionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private RuntimeBeanReference getMessageCodesResolver(Element element) {
	if (element.hasAttribute("message-codes-resolver")) {
		return new RuntimeBeanReference(element.getAttribute("message-codes-resolver"));
	}
	else {
		return null;
	}
}
 
Example #30
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 5 votes vote down vote up
private String registerPersisterBean(
		ReferenceFactory referenceFactory,
		PersistenceSupportBeanFactory persistenceFactory,
		StatefulController statefulContollerAnnotation,
		Class<?> statefulClass,
		String repoBeanId,
		BeanDefinition repoBeanDefinitionFactory,
		List<RuntimeBeanReference> stateBeans,
		BeanDefinitionRegistry reg) {

	String persisterId = statefulContollerAnnotation.persisterId();

	if (StringUtils.isEmpty(persisterId)) {
		if (persistenceFactory == null) {
			throw new RuntimeException("PersistenceFactory is undefined and no persister bean was specified in the StatefulController Annotation for " + statefulContollerAnnotation.clazz());
		}
		String startStateId = referenceFactory.getStateId(statefulContollerAnnotation.startState());
		persisterId = referenceFactory.getPersisterId();
		reg.registerBeanDefinition(
				persisterId,
				persistenceFactory.buildPersisterBean(
						statefulClass,
						repoBeanId,
						repoBeanDefinitionFactory,
						statefulContollerAnnotation.stateField(),
						startStateId,
						stateBeans));
	}

	return persisterId;
}