Search in sources :

Example 91 with RuntimeBeanReference

use of org.springframework.beans.factory.config.RuntimeBeanReference in project dubbo by alibaba.

the class ServiceAnnotationBeanPostProcessor method buildServiceBeanDefinition.

private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class<?> interfaceClass, String annotatedServiceBeanName) {
    BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class).addConstructorArgValue(service).addPropertyReference("ref", annotatedServiceBeanName).addPropertyValue("interface", interfaceClass.getName());
    /**
     * Add {@link com.alibaba.dubbo.config.ProviderConfig} Bean reference
     */
    String providerConfigBeanName = service.provider();
    if (StringUtils.hasText(providerConfigBeanName)) {
        addPropertyReference(builder, "provider", providerConfigBeanName);
    }
    /**
     * Add {@link com.alibaba.dubbo.config.MonitorConfig} Bean reference
     */
    String monitorConfigBeanName = service.monitor();
    if (StringUtils.hasText(monitorConfigBeanName)) {
        addPropertyReference(builder, "monitor", monitorConfigBeanName);
    }
    /**
     * Add {@link com.alibaba.dubbo.config.ApplicationConfig} Bean reference
     */
    String applicationConfigBeanName = service.application();
    if (StringUtils.hasText(applicationConfigBeanName)) {
        addPropertyReference(builder, "application", applicationConfigBeanName);
    }
    /**
     * Add {@link com.alibaba.dubbo.config.ModuleConfig} Bean reference
     */
    String moduleConfigBeanName = service.module();
    if (StringUtils.hasText(moduleConfigBeanName)) {
        addPropertyReference(builder, "module", moduleConfigBeanName);
    }
    /**
     * Add {@link com.alibaba.dubbo.config.RegistryConfig} Bean reference
     */
    String[] registryConfigBeanNames = service.registry();
    List<RuntimeBeanReference> registryRuntimeBeanReferences = toRuntimeBeanReferences(registryConfigBeanNames);
    if (!registryRuntimeBeanReferences.isEmpty()) {
        builder.addPropertyValue("registries", registryRuntimeBeanReferences);
    }
    /**
     * Add {@link com.alibaba.dubbo.config.ProtocolConfig} Bean reference
     */
    String[] protocolConfigBeanNames = service.protocol();
    List<RuntimeBeanReference> protocolRuntimeBeanReferences = toRuntimeBeanReferences(protocolConfigBeanNames);
    if (!registryRuntimeBeanReferences.isEmpty()) {
        builder.addPropertyValue("protocols", protocolRuntimeBeanReferences);
    }
    return builder.getBeanDefinition();
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) ServiceBean(com.alibaba.dubbo.config.spring.ServiceBean) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference)

Example 92 with RuntimeBeanReference

use of org.springframework.beans.factory.config.RuntimeBeanReference in project dubbo by alibaba.

the class ServiceAnnotationBeanPostProcessor method toRuntimeBeanReferences.

private ManagedList<RuntimeBeanReference> toRuntimeBeanReferences(String... beanNames) {
    ManagedList<RuntimeBeanReference> runtimeBeanReferences = new ManagedList<RuntimeBeanReference>();
    if (!ObjectUtils.isEmpty(beanNames)) {
        for (String beanName : beanNames) {
            String resolvedBeanName = environment.resolvePlaceholders(beanName);
            runtimeBeanReferences.add(new RuntimeBeanReference(resolvedBeanName));
        }
    }
    return runtimeBeanReferences;
}
Also used : ManagedList(org.springframework.beans.factory.support.ManagedList) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference)

Example 93 with RuntimeBeanReference

use of org.springframework.beans.factory.config.RuntimeBeanReference in project dubbo by alibaba.

the class DubboBeanDefinitionParser method parse.

@SuppressWarnings("unchecked")
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
    RootBeanDefinition beanDefinition = new RootBeanDefinition();
    beanDefinition.setBeanClass(beanClass);
    beanDefinition.setLazyInit(false);
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            if (ProtocolConfig.class.equals(beanClass)) {
                generatedBeanName = "dubbo";
            } else {
                generatedBeanName = element.getAttribute("interface");
            }
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        beanDefinition.getPropertyValues().addPropertyValue("id", id);
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
            BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
            PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
            if (property != null) {
                Object value = property.getValue();
                if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
                    definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
                }
            }
        }
    } else if (ServiceBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(ReflectUtils.forName(className));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    } else if (ProviderConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
    } else if (ConsumerConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
    }
    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) {
            Class<?> type = setter.getParameterTypes()[0];
            String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
            props.add(property);
            Method getter = null;
            try {
                getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
            } catch (NoSuchMethodException e) {
                try {
                    getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
                } catch (NoSuchMethodException e2) {
                }
            }
            if (getter == null || !Modifier.isPublic(getter.getModifiers()) || !type.equals(getter.getReturnType())) {
                continue;
            }
            if ("parameters".equals(property)) {
                parameters = parseParameters(element.getChildNodes(), beanDefinition);
            } else if ("methods".equals(property)) {
                parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
            } else if ("arguments".equals(property)) {
                parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
            } else {
                String value = element.getAttribute(property);
                if (value != null) {
                    value = value.trim();
                    if (value.length() > 0) {
                        if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
                            RegistryConfig registryConfig = new RegistryConfig();
                            registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
                            beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig);
                        } else if ("registry".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("registries", value, beanDefinition, parserContext);
                        } else if ("provider".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("providers", value, beanDefinition, parserContext);
                        } else if ("protocol".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("protocols", value, beanDefinition, parserContext);
                        } else {
                            Object reference;
                            if (isPrimitive(type)) {
                                if ("async".equals(property) && "false".equals(value) || "timeout".equals(property) && "0".equals(value) || "delay".equals(property) && "0".equals(value) || "version".equals(property) && "0.0.0".equals(value) || "stat".equals(property) && "-1".equals(value) || "reliable".equals(property) && "false".equals(value)) {
                                    // backward compatibility for the default value in old version's xsd
                                    value = null;
                                }
                                reference = value;
                            } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) && (!parserContext.getRegistry().containsBeanDefinition(value) || !ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
                                if ("dubbo:provider".equals(element.getTagName())) {
                                    logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />");
                                }
                                // backward compatibility
                                ProtocolConfig protocol = new ProtocolConfig();
                                protocol.setName(value);
                                reference = protocol;
                            } else if ("onreturn".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String returnRef = value.substring(0, index);
                                String returnMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(returnRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod);
                            } else if ("onthrow".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String throwRef = value.substring(0, index);
                                String throwMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(throwRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod);
                            } else if ("oninvoke".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String invokeRef = value.substring(0, index);
                                String invokeRefMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(invokeRef);
                                beanDefinition.getPropertyValues().addPropertyValue("oninvokeMethod", invokeRefMethod);
                            } else {
                                if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
                                    BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                                    if (!refBean.isSingleton()) {
                                        throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>");
                                    }
                                }
                                reference = new RuntimeBeanReference(value);
                            }
                            beanDefinition.getPropertyValues().addPropertyValue(property, reference);
                        }
                    }
                }
            }
        }
    }
    NamedNodeMap attributes = element.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = attributes.item(i);
        String name = node.getLocalName();
        if (!props.contains(name)) {
            if (parameters == null) {
                parameters = new ManagedMap();
            }
            String value = node.getNodeValue();
            parameters.put(name, new TypedStringValue(value, String.class));
        }
    }
    if (parameters != null) {
        beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return beanDefinition;
}
Also used : Node(org.w3c.dom.Node) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ServiceBean(com.alibaba.dubbo.config.spring.ServiceBean) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) Protocol(com.alibaba.dubbo.rpc.Protocol) ManagedMap(org.springframework.beans.factory.support.ManagedMap) HashSet(java.util.HashSet) NamedNodeMap(org.w3c.dom.NamedNodeMap) PropertyValue(org.springframework.beans.PropertyValue) Method(java.lang.reflect.Method) ReferenceBean(com.alibaba.dubbo.config.spring.ReferenceBean) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue)

Example 94 with RuntimeBeanReference

use of org.springframework.beans.factory.config.RuntimeBeanReference in project dubbo by alibaba.

the class DubboBeanDefinitionParser method parseProperties.

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=\"...\" />");
                        }
                    }
                }
            }
        }
    }
}
Also used : Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference)

Example 95 with RuntimeBeanReference

use of org.springframework.beans.factory.config.RuntimeBeanReference in project hudson-2.x by hudson.

the class BeanBuilder method invokeBeanDefiningMethod.

/**
	 * This method is called when a bean definition node is called
	 *
	 * @param name The name of the bean to define
	 * @param args The arguments to the bean. The first argument is the class name, the last argument is sometimes a closure. All
	 * the arguments in between are constructor arguments
	 * @return The bean configuration instance
	 */
private BeanConfiguration invokeBeanDefiningMethod(String name, Object[] args) {
    BeanConfiguration old = currentBeanConfig;
    try {
        if (args[0] instanceof Class) {
            Class beanClass = args[0] instanceof Class ? (Class) args[0] : args[0].getClass();
            if (args.length >= 1) {
                if (args[args.length - 1] instanceof Closure) {
                    if (args.length - 1 != 1) {
                        Object[] constructorArgs = ArrayUtils.subarray(args, 1, args.length - 1);
                        filterGStringReferences(constructorArgs);
                        if (name.equals(ANONYMOUS_BEAN))
                            currentBeanConfig = springConfig.createSingletonBean(beanClass, Arrays.asList(constructorArgs));
                        else
                            currentBeanConfig = springConfig.addSingletonBean(name, beanClass, Arrays.asList(constructorArgs));
                    } else {
                        if (name.equals(ANONYMOUS_BEAN))
                            currentBeanConfig = springConfig.createSingletonBean(beanClass);
                        else
                            currentBeanConfig = springConfig.addSingletonBean(name, beanClass);
                    }
                } else {
                    Object[] constructorArgs = ArrayUtils.subarray(args, 1, args.length);
                    filterGStringReferences(constructorArgs);
                    if (name.equals(ANONYMOUS_BEAN))
                        currentBeanConfig = springConfig.createSingletonBean(beanClass, Arrays.asList(constructorArgs));
                    else
                        currentBeanConfig = springConfig.addSingletonBean(name, beanClass, Arrays.asList(constructorArgs));
                }
            }
        } else if (args[0] instanceof RuntimeBeanReference) {
            currentBeanConfig = springConfig.addSingletonBean(name);
            currentBeanConfig.setFactoryBean(((RuntimeBeanReference) args[0]).getBeanName());
        } else if (args[0] instanceof Map) {
            currentBeanConfig = springConfig.addSingletonBean(name);
            Map.Entry factoryBeanEntry = (Map.Entry) ((Map) args[0]).entrySet().iterator().next();
            currentBeanConfig.setFactoryBean(factoryBeanEntry.getKey().toString());
            currentBeanConfig.setFactoryMethod(factoryBeanEntry.getValue().toString());
        } else if (args[0] instanceof Closure) {
            currentBeanConfig = springConfig.addAbstractBean(name);
        } else {
            Object[] constructorArgs;
            if (args[args.length - 1] instanceof Closure) {
                constructorArgs = ArrayUtils.subarray(args, 0, args.length - 1);
            } else {
                constructorArgs = ArrayUtils.subarray(args, 0, args.length);
            }
            filterGStringReferences(constructorArgs);
            currentBeanConfig = new DefaultBeanConfiguration(name, null, Arrays.asList(constructorArgs));
            springConfig.addBeanConfiguration(name, currentBeanConfig);
        }
        if (args[args.length - 1] instanceof Closure) {
            Closure callable = (Closure) args[args.length - 1];
            callable.setDelegate(this);
            callable.setResolveStrategy(Closure.DELEGATE_FIRST);
            callable.call(new Object[] { currentBeanConfig });
        }
        return currentBeanConfig;
    } finally {
        currentBeanConfig = old;
    }
}
Also used : Entry(java.util.Map.Entry) Entry(java.util.Map.Entry) Closure(groovy.lang.Closure) MetaClass(groovy.lang.MetaClass) GroovyObject(groovy.lang.GroovyObject) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) HashMap(java.util.HashMap) Map(java.util.Map) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Aggregations

RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)156 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)86 Element (org.w3c.dom.Element)47 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)39 BeanComponentDefinition (org.springframework.beans.factory.parsing.BeanComponentDefinition)33 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)32 ManagedList (org.springframework.beans.factory.support.ManagedList)27 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)24 Test (org.junit.Test)21 ManagedMap (org.springframework.beans.factory.support.ManagedMap)20 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)16 ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)15 GroovyObject (groovy.lang.GroovyObject)12 TestBean (org.springframework.tests.sample.beans.TestBean)12 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)11 Map (java.util.Map)10 Node (org.w3c.dom.Node)10 HashMap (java.util.HashMap)9 CompositeComponentDefinition (org.springframework.beans.factory.parsing.CompositeComponentDefinition)9 ITestBean (org.springframework.tests.sample.beans.ITestBean)8