org.springframework.beans.factory.config.RuntimeBeanReference源码实例Demo

类org.springframework.beans.factory.config.RuntimeBeanReference源码实例Demo

下面列出了org.springframework.beans.factory.config.RuntimeBeanReference 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dubbo-2.6.5   文件: DubboBeanDefinitionParser.java
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));
                    }
                }
            }
        }
    }
}
 
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);
}
 
@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;
	}
}
 
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;
}
 
@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());
}
 
源代码6 项目: blog_demos   文件: GroovyBeanDefinitionReader.java
/**
 * 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;
}
 
源代码7 项目: statefulj   文件: StatefulFactory.java
/**
 * @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);
}
 
@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);
}
 
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);
}
 
源代码10 项目: dubbo3   文件: DubboBeanDefinitionParser.java
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=\"...\" />");
                        }
                    }
                }
            }
        }
    }
}
 
源代码11 项目: Jupiter   文件: JupiterBeanDefinitionParser.java
@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);
    }
}
 
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;
}
 
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;
	}
}
 
@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);
}
 
/**
 * 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;
}
 
/**
 * 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;
}
 
@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;
	}
}
 
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);
}
 
@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);
	}
}
 
/**
 * 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));
}
 
@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());
}
 
/**
 * 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;
}
 
@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);
	}
}
 
源代码24 项目: dubbox-hystrix   文件: DubboBeanDefinitionParser.java
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=\"...\" />");
                        }
                    }
                }
            }
        }
    }
}
 
@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());
}
 
@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);
}
 
@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);
}
 
private static void registerCacheAdvisor(Element element, ParserContext parserContext) {
	if (!parserContext.getRegistry().containsBeanDefinition(CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME)) {
		Object eleSource = parserContext.extractSource(element);

		// Create the CacheOperationSource definition.
		RootBeanDefinition sourceDef = new RootBeanDefinition("org.springframework.cache.annotation.AnnotationCacheOperationSource");
		sourceDef.setSource(eleSource);
		sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);

		// Create the CacheInterceptor definition.
		RootBeanDefinition interceptorDef = new RootBeanDefinition(CacheInterceptor.class);
		interceptorDef.setSource(eleSource);
		interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		parseCacheResolution(element, interceptorDef, false);
		parseErrorHandler(element, interceptorDef);
		CacheNamespaceHandler.parseKeyGenerator(element, interceptorDef);
		interceptorDef.getPropertyValues().add("cacheOperationSources", new RuntimeBeanReference(sourceName));
		String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);

		// Create the CacheAdvisor definition.
		RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryCacheOperationSourceAdvisor.class);
		advisorDef.setSource(eleSource);
		advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		advisorDef.getPropertyValues().add("cacheOperationSource", new RuntimeBeanReference(sourceName));
		advisorDef.getPropertyValues().add("adviceBeanName", interceptorName);
		if (element.hasAttribute("order")) {
			advisorDef.getPropertyValues().add("order", element.getAttribute("order"));
		}
		parserContext.getRegistry().registerBeanDefinition(CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME, advisorDef);

		CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource);
		compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName));
		compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName));
		compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME));
		parserContext.registerComponent(compositeDef);
	}
}
 
@Test
public void runtimeBeanReference() {
	RuntimeBeanReference master = new RuntimeBeanReference("name");
	RuntimeBeanReference equal = new RuntimeBeanReference("name");
	RuntimeBeanReference notEqual = new RuntimeBeanReference("someOtherName");
	RuntimeBeanReference subclass = new RuntimeBeanReference("name") {
	};
	assertEqualsAndHashCodeContracts(master, equal, notEqual, subclass);
}
 
private RuntimeBeanReference runnableReference(String ref, String method, Element taskElement, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
			"org.springframework.scheduling.support.ScheduledMethodRunnable");
	builder.addConstructorArgReference(ref);
	builder.addConstructorArgValue(method);
	return beanReference(taskElement, parserContext, builder);
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类方法
 同包方法