/** * 修改配置Bean定义,使用静态方法{@link ConfigBeanFactory#FACTORY_METHOD}来实例化。 * * @param registry * @param beanName * @param beanDefinition * @param propertyName * @param converterType */ public static void setConfigBeanFactoryMethod(BeanDefinitionRegistry registry, String beanName, BeanDefinition beanDefinition, String propertyName, Class<?> converterType) { // 注册ConfigBeanPropertyResolver registerConfigBeanPropertyResolver(registry); // 注册ConfigBeanConversionService registerConfigBeanConversionService(registry); String beanClassName = beanDefinition.getBeanClassName(); beanDefinition.setBeanClassName(ConfigBeanFactory.class.getName()); beanDefinition.setFactoryMethodName(ConfigBeanFactory.FACTORY_METHOD); ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); constructorArgumentValues.addGenericArgumentValue(propertyName, String.class.getName()); constructorArgumentValues.addGenericArgumentValue(beanClassName, Class.class.getName()); constructorArgumentValues.addGenericArgumentValue(converterType); constructorArgumentValues.addGenericArgumentValue(new RuntimeBeanReference(CONFIG_BEAN_PROPERTY_RESOLVER_BEAN_NAME)); constructorArgumentValues.addGenericArgumentValue(new RuntimeBeanReference(CONFIG_BEAN_CONVERSION_SERVICE_BEAN_NAME)); beanDefinition.getConstructorArgumentValues().addArgumentValues(constructorArgumentValues); }
@Override protected void parseNested(Element element, ParserContext parserContext, BeanDefinitionBuilder builder, BeanDefinition bd) { Class<?> apiClass; try { apiClass = Class.forName(helper.getAttribute(element, RedissonNamespaceParserSupport.CLASS_ATTRIBUTE)); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( "The class [" + helper.getAttribute(element, RedissonNamespaceParserSupport.CLASS_ATTRIBUTE) + "] specified in \"api-class\" attribute has not " + "found. Please check the class path.", ex); } builder.addPropertyValue("targetObject", new RuntimeBeanReference( helper.getAttribute(element, RedissonNamespaceParserSupport.LIVE_OBJECT_SERVICE_REF_ATTRIBUTE))); builder.addPropertyValue("targetMethod", "registerClass"); builder.addPropertyValue("arguments", new Object[] {apiClass}); }
@Override protected void parseNested(Element element, ParserContext parserContext, BeanDefinitionBuilder builder, BeanDefinition bd) { Class<?> apiClass; try { apiClass = Class.forName(helper.getAttribute(element, RedissonNamespaceParserSupport.API_CLASS_ATTRIBUTE)); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( "The class [" + helper.getAttribute(element, RedissonNamespaceParserSupport.API_CLASS_ATTRIBUTE) + "] specified in \"" + RedissonNamespaceParserSupport.API_CLASS_ATTRIBUTE + "\" attribute has not " + "found. Please check the class path.", ex); } builder.addPropertyValue("targetObject", new RuntimeBeanReference( helper.getAttribute(element, RedissonNamespaceParserSupport.REMOTE_SERVICE_REF_ATTRIBUTE))); builder.addPropertyValue("targetMethod", "get"); builder.addPropertyValue("arguments", new Object[] {apiClass}); }
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 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=\"...\" />"); } } } } } } }
private void addRefIfNeeded(Object v, List<String> refs) { if(v == null) return; if(v instanceof RuntimeBeanReference) { RuntimeBeanReference r = (RuntimeBeanReference)v; String name = r.getBeanName(); addRefIfNeeded(name, refs); if(name == null || name.length() == 0) { System.err.println("Warning - empty reference " + r); } } else if(v instanceof BeanDefinitionHolder) { // Nested bean definition BeanDefinitionHolder bdh = (BeanDefinitionHolder)v; processBeanDefinition(bdh.getBeanName(), bdh.getBeanDefinition()); } else if(v instanceof ManagedList<?>) { ManagedList<?> ml = (ManagedList<?>)v; for(Object le : ml) { addRefIfNeeded(le, refs); } // } else { // System.err.println(v.getClass()); } }
@Override protected String resolveId(Element el, AbstractBeanDefinition def, ParserContext ctx) { String id = super.resolveId(el, def, ctx); deferredBaseBeans.forEach((baseBeanBuilder, baseBeanName) -> { baseBeanBuilder.addPropertyValue("source", new RuntimeBeanReference(id)); AbstractBeanDefinition baseBean = baseBeanBuilder.getBeanDefinition(); if (baseBeanName == null) { ctx.getRegistry().registerBeanDefinition(ctx.getReaderContext().generateBeanName(baseBean), baseBean); } else { ctx.getRegistry().registerBeanDefinition(baseBeanName, baseBean); } }); return id; }
private Optional<RuntimeBeanReference> parseMessagingBackPressure(Element el, ParserContext ctx) { Element backPressureEl = getChildElementByTagName(el, "back-pressure"); if (backPressureEl != null) { BeanDefinitionBuilder backPressure = newBean(MessagingBackPressureConfig.class, backPressureEl); Element outboundEl = getChildElementByTagName(backPressureEl, "outbound"); Element inboundEl = getChildElementByTagName(backPressureEl, "inbound"); if (outboundEl != null) { setProperty(backPressure, outboundEl, "outLowWatermark", "low-watermark"); setProperty(backPressure, outboundEl, "outHighWatermark", "high-watermark"); setProperty(backPressure, outboundEl, "outOverflowPolicy", "overflow"); } if (inboundEl != null) { setProperty(backPressure, inboundEl, "inLowWatermark", "low-watermark"); setProperty(backPressure, inboundEl, "inHighWatermark", "high-watermark"); } return Optional.of(registerInnerBean(backPressure, ctx)); } else { return Optional.empty(); } }
private Optional<RuntimeBeanReference> parseClusterMetricsService(Element rootEl, ParserContext ctx) { Element metricsEl = getChildElementByTagName(rootEl, "cluster-metrics"); if (metricsEl != null) { BeanDefinitionBuilder metrics = newBean(ClusterMetricsServiceFactory.class, metricsEl); setProperty(metrics, metricsEl, "enabled", "enabled"); setProperty(metrics, metricsEl, "replicationInterval", "replication-interval-ms"); setBeanOrRef(metrics, metricsEl, "replicationFilter", "filter", ctx); String id = metricsEl.getAttribute("id"); if (!id.isEmpty()) { deferredBaseBeans.put(newLazyBean(ClusterMetricsServiceBean.class, metricsEl), id); } return Optional.of(registerInnerBean(metrics, ctx)); } else { return Optional.empty(); } }
private Optional<RuntimeBeanReference> parseRefOrBean(Element elem, ParserContext ctx) { if (elem != null) { String ref = elem.getAttribute("ref").trim(); Element beanEl = getChildElementByTagName(elem, "bean"); if (!ref.isEmpty() && beanEl != null) { String name = elem.getLocalName(); ctx.getReaderContext().error('<' + name + ">'s 'ref' attribute can't be mixed with nested <bean> element.", elem); } else if (!ref.isEmpty()) { return Optional.of(new RuntimeBeanReference(ref)); } else if (beanEl != null) { BeanDefinitionHolder holder = ctx.getDelegate().parseBeanDefinitionElement(beanEl); ctx.registerBeanComponent(new BeanComponentDefinition(holder.getBeanDefinition(), holder.getBeanName())); return Optional.of(new RuntimeBeanReference(holder.getBeanName())); } } return Optional.empty(); }
@Override protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition( RepositoryConfigurationSource configurationSource) { RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition(TarantoolKeyValueTemplate.class); ConstructorArgumentValues constructorArgumentValuesForKeyValueTemplate = new ConstructorArgumentValues(); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(0, new RuntimeBeanReference(TARANTOOL_OPS_IMPL_BEAN_NAME)); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(1, new RuntimeBeanReference(MAPPING_CONTEXT_BEAN_NAME)); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(2, new RuntimeBeanReference(TARANTOOL_CONVERTER_BEAN_NAME)); keyValueTemplateDefinition.setConstructorArgumentValues(constructorArgumentValuesForKeyValueTemplate); return keyValueTemplateDefinition; }
private AbstractBeanDefinition buildExporter(ServiceMetadata metadata) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(EXPORTER_CLASS); // add properties builder.addPropertyValue(EXPORTER_RANKING_PROP, metadata.getRanking()); builder.addPropertyValue(EXPORTER_INTFS_PROP, metadata.getInterfaces()); builder.addPropertyValue(EXPORTER_PROPS_PROP, metadata.getServiceProperties()); builder.addPropertyValue(EXPORTER_AUTO_EXPORT_PROP, DefaultInterfaceDetector.values()[metadata.getAutoExport() - 1]); BeanMetadataElement beanMetadata = BeanMetadataElementFactory.buildBeanMetadata(metadata.getServiceComponent()); if (beanMetadata instanceof RuntimeBeanReference) { builder.addPropertyValue(EXPORTER_TARGET_BEAN_NAME_PROP, beanMetadata); } else { builder.addPropertyValue(EXPORTER_TARGET_BEAN_PROP, beanMetadata); } // FIXME: add registration listeners return builder.getBeanDefinition(); }
private Object parseRefElement(Element ele) { // A generic reference to any name of any component. String refName = ele.getAttribute(COMPONENT_ID_ATTR); if (!StringUtils.hasLength(refName)) { error("'" + COMPONENT_ID_ATTR + "' is required for <ref> element", ele); return null; } if (!StringUtils.hasText(refName)) { error("<ref> element contains empty target attribute", ele); return null; } RuntimeBeanReference ref = new InstanceEqualityRuntimeBeanReference(refName); ref.setSource(parserContext.extractSource(ele)); return ref; }
private void tag(Collection<ValueHolder> values, String name, BeanDefinition definition) { boolean trace = log.isTraceEnabled(); for (ValueHolder value : values) { Object val = value.getValue(); if (val instanceof BeanMetadataElement) { if (val instanceof RuntimeBeanReference) { String beanName = ((RuntimeBeanReference) val).getBeanName(); if (trace) { log.trace("Adding (cycle breaking) depends-on on " + name + " to " + beanName); } addSyntheticDependsOn(definition, beanName); } } } }
/** * Resolve a reference to another bean in the factory. */ private Object resolveReference(Object argName, RuntimeBeanReference ref) { try { String refName = ref.getBeanName(); refName = String.valueOf(evaluate(refName)); if (ref.isToParent()) { if (this.beanFactory.getParentBeanFactory() == null) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Can't resolve reference to bean '" + refName + "' in parent factory: no parent factory available"); } return this.beanFactory.getParentBeanFactory().getBean(refName); } else { Object bean = this.beanFactory.getBean(refName); this.beanFactory.registerDependentBean(refName, this.beanName); return bean; } } catch (BeansException ex) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex); } }
@Override public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { if (node instanceof Attr) { Attr attr = (Attr) node; String propertyName = parserContext.getDelegate().getLocalName(attr); String propertyValue = attr.getValue(); MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues(); if (pvs.contains(propertyName)) { parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " + "both <property> and inline syntax. Only one approach may be used per property.", attr); } if (propertyName.endsWith(REF_SUFFIX)) { propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length()); pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue)); } else { pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue); } } return definition; }
/** * 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; }
/** * Checks whether there are any {@link RuntimeBeanReference}s inside the List * and converts it to a 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; }
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); }
@Override protected void postProcess(BeanDefinitionBuilder definitionBuilder, Element element) { Object envValue = DomUtils.getChildElementValueByTagName(element, ENVIRONMENT); if (envValue != null) { // Specific environment settings defined, overriding any shared properties. definitionBuilder.addPropertyValue(JNDI_ENVIRONMENT, envValue); } else { // Check whether there is a reference to shared environment properties... String envRef = element.getAttribute(ENVIRONMENT_REF); if (StringUtils.hasLength(envRef)) { definitionBuilder.addPropertyValue(JNDI_ENVIRONMENT, new RuntimeBeanReference(envRef)); } } String lazyInit = element.getAttribute(LAZY_INIT_ATTRIBUTE); if (StringUtils.hasText(lazyInit) && !DEFAULT_VALUE.equals(lazyInit)) { definitionBuilder.setLazyInit(TRUE_VALUE.equals(lazyInit)); } }
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doParse(element, parserContext, builder); String defaultValue = element.getAttribute(DEFAULT_VALUE); String defaultRef = element.getAttribute(DEFAULT_REF); if (StringUtils.hasLength(defaultValue)) { if (StringUtils.hasLength(defaultRef)) { parserContext.getReaderContext().error("<jndi-lookup> element is only allowed to contain either " + "'default-value' attribute OR 'default-ref' attribute, not both", element); } builder.addPropertyValue(DEFAULT_OBJECT, defaultValue); } else if (StringUtils.hasLength(defaultRef)) { builder.addPropertyValue(DEFAULT_OBJECT, new RuntimeBeanReference(defaultRef)); } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void postProcessBeanFactory( ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { String[] igniteConfigNames = configurableListableBeanFactory.getBeanNamesForType(IgniteConfiguration.class); if (igniteConfigNames.length != 1) { throw new IllegalArgumentException("Spring config must contain exactly one ignite configuration!"); } String[] activeStoreConfigNames = configurableListableBeanFactory.getBeanNamesForType(BaseActiveStoreConfiguration.class); if (activeStoreConfigNames.length != 1) { throw new IllegalArgumentException("Spring config must contain exactly one active store configuration!"); } BeanDefinition igniteConfigDef = configurableListableBeanFactory.getBeanDefinition(igniteConfigNames[0]); MutablePropertyValues propertyValues = igniteConfigDef.getPropertyValues(); if (!propertyValues.contains(USER_ATTRS_PROP_NAME)) { propertyValues.add(USER_ATTRS_PROP_NAME, new ManagedMap()); } PropertyValue propertyValue = propertyValues.getPropertyValue(USER_ATTRS_PROP_NAME); Map userAttrs = (Map)propertyValue.getValue(); TypedStringValue key = new TypedStringValue(CONFIG_USER_ATTR); RuntimeBeanReference value = new RuntimeBeanReference(beanName); userAttrs.put(key, value); }
/** * Checks whether there are any {@link RuntimeBeanReference}s 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<Object, Object>(); managedMap.putAll(map); return managedMap; } return map; }
@Override @SuppressWarnings("unchecked") protected void doParse(Element element, BeanDefinitionBuilder dwrController) { List<Object> configurators = new ManagedList(); configurators.add(new RuntimeBeanReference(ConfigurationParser.DEFAULT_SPRING_CONFIGURATOR_ID)); dwrController.addPropertyValue("configurators", configurators); String debug = element.getAttribute("debug"); if (StringUtils.hasText(debug)) { dwrController.addPropertyValue("debug", debug); } parseControllerParameters(dwrController, element); }
protected void doParse(Element element, BeanDefinitionBuilder bean) { final ManagedList<Object> actions = new ManagedList<>(); final NodeList actionNodes = element.getElementsByTagName("*"); if (actionNodes != null && actionNodes.getLength() != 0) { for (int i = 0; i < actionNodes.getLength(); i++) { final Node node = actionNodes.item(i); final String type = node.getLocalName(); if (type.equalsIgnoreCase("method")) { actions.add(node.getTextContent()); } else if (type.equalsIgnoreCase("action")) { actions.add(new RuntimeBeanReference(node.getTextContent())); } else { throw new IllegalArgumentException("Unknown element type: " + type); } } } bean.addPropertyValue("actions", actions); }
protected void doParse(Element element, BeanDefinitionBuilder bean) { final Map<Object, Object> configuration = new ManagedMap<>(); final Node keywordValueNode = element .getElementsByTagNameNS("http://xdcrafts.github.com/schema/flower", "keyword-value") .item(0); final Node predicateNode = element .getElementsByTagNameNS("http://xdcrafts.github.com/schema/flower", "predicate") .item(0); if (keywordValueNode != null) { configuration.put("keyword-value", keywordValueNode.getTextContent()); } if (predicateNode != null) { configuration.put("predicate", new RuntimeBeanReference(predicateNode.getTextContent())); } bean .addPropertyReference("action", element.getAttribute("action")) .addPropertyValue("configuration", configuration); }
/** * 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; }