Search in sources :

Example 21 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project spring-framework by spring-projects.

the class ApplicationContextExpressionTests method prototypeCreationReevaluatesExpressions.

@Test
public void prototypeCreationReevaluatesExpressions() {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
    GenericConversionService cs = new GenericConversionService();
    cs.addConverter(String.class, String.class, new Converter<String, String>() {

        @Override
        public String convert(String source) {
            return source.trim();
        }
    });
    ac.getBeanFactory().registerSingleton(GenericApplicationContext.CONVERSION_SERVICE_BEAN_NAME, cs);
    RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
    rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    rbd.getPropertyValues().add("country", "#{systemProperties.country}");
    rbd.getPropertyValues().add("country2", new TypedStringValue("-#{systemProperties.country}-"));
    ac.registerBeanDefinition("test", rbd);
    ac.refresh();
    try {
        System.getProperties().put("name", "juergen1");
        System.getProperties().put("country", " UK1 ");
        PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
        assertEquals("juergen1", tb.getName());
        assertEquals("UK1", tb.getCountry());
        assertEquals("-UK1-", tb.getCountry2());
        System.getProperties().put("name", "juergen2");
        System.getProperties().put("country", "  UK2  ");
        tb = (PrototypeTestBean) ac.getBean("test");
        assertEquals("juergen2", tb.getName());
        assertEquals("UK2", tb.getCountry());
        assertEquals("-UK2-", tb.getCountry2());
    } finally {
        System.getProperties().remove("name");
        System.getProperties().remove("country");
    }
}
Also used : GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) Test(org.junit.Test)

Example 22 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project spring-framework by spring-projects.

the class CacheAdviceParser method parseDefinitionSource.

private RootBeanDefinition parseDefinitionSource(Element definition, ParserContext parserContext) {
    Props prop = new Props(definition);
    // add cacheable first
    ManagedMap<TypedStringValue, Collection<CacheOperation>> cacheOpMap = new ManagedMap<>();
    cacheOpMap.setSource(parserContext.extractSource(definition));
    List<Element> cacheableCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHEABLE_ELEMENT);
    for (Element opElement : cacheableCacheMethods) {
        String name = prop.merge(opElement, parserContext.getReaderContext());
        TypedStringValue nameHolder = new TypedStringValue(name);
        nameHolder.setSource(parserContext.extractSource(opElement));
        CacheableOperation.Builder builder = prop.merge(opElement, parserContext.getReaderContext(), new CacheableOperation.Builder());
        builder.setUnless(getAttributeValue(opElement, "unless", ""));
        builder.setSync(Boolean.valueOf(getAttributeValue(opElement, "sync", "false")));
        Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
        if (col == null) {
            col = new ArrayList<>(2);
            cacheOpMap.put(nameHolder, col);
        }
        col.add(builder.build());
    }
    List<Element> evictCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHE_EVICT_ELEMENT);
    for (Element opElement : evictCacheMethods) {
        String name = prop.merge(opElement, parserContext.getReaderContext());
        TypedStringValue nameHolder = new TypedStringValue(name);
        nameHolder.setSource(parserContext.extractSource(opElement));
        CacheEvictOperation.Builder builder = prop.merge(opElement, parserContext.getReaderContext(), new CacheEvictOperation.Builder());
        String wide = opElement.getAttribute("all-entries");
        if (StringUtils.hasText(wide)) {
            builder.setCacheWide(Boolean.valueOf(wide.trim()));
        }
        String after = opElement.getAttribute("before-invocation");
        if (StringUtils.hasText(after)) {
            builder.setBeforeInvocation(Boolean.valueOf(after.trim()));
        }
        Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
        if (col == null) {
            col = new ArrayList<>(2);
            cacheOpMap.put(nameHolder, col);
        }
        col.add(builder.build());
    }
    List<Element> putCacheMethods = DomUtils.getChildElementsByTagName(definition, CACHE_PUT_ELEMENT);
    for (Element opElement : putCacheMethods) {
        String name = prop.merge(opElement, parserContext.getReaderContext());
        TypedStringValue nameHolder = new TypedStringValue(name);
        nameHolder.setSource(parserContext.extractSource(opElement));
        CachePutOperation.Builder builder = prop.merge(opElement, parserContext.getReaderContext(), new CachePutOperation.Builder());
        builder.setUnless(getAttributeValue(opElement, "unless", ""));
        Collection<CacheOperation> col = cacheOpMap.get(nameHolder);
        if (col == null) {
            col = new ArrayList<>(2);
            cacheOpMap.put(nameHolder, col);
        }
        col.add(builder.build());
    }
    RootBeanDefinition attributeSourceDefinition = new RootBeanDefinition(NameMatchCacheOperationSource.class);
    attributeSourceDefinition.setSource(parserContext.extractSource(definition));
    attributeSourceDefinition.getPropertyValues().add("nameMap", cacheOpMap);
    return attributeSourceDefinition;
}
Also used : Element(org.w3c.dom.Element) CachePutOperation(org.springframework.cache.interceptor.CachePutOperation) CacheableOperation(org.springframework.cache.interceptor.CacheableOperation) CacheEvictOperation(org.springframework.cache.interceptor.CacheEvictOperation) CacheOperation(org.springframework.cache.interceptor.CacheOperation) Collection(java.util.Collection) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 23 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project spring-framework by spring-projects.

the class DatabasePopulatorConfigUtils method createDatabasePopulator.

private static BeanDefinition createDatabasePopulator(Element element, List<Element> scripts, String execution) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CompositeDatabasePopulator.class);
    boolean ignoreFailedDrops = element.getAttribute("ignore-failures").equals("DROPS");
    boolean continueOnError = element.getAttribute("ignore-failures").equals("ALL");
    ManagedList<BeanMetadataElement> delegates = new ManagedList<>();
    for (Element scriptElement : scripts) {
        String executionAttr = scriptElement.getAttribute("execution");
        if (!StringUtils.hasText(executionAttr)) {
            executionAttr = "INIT";
        }
        if (!execution.equals(executionAttr)) {
            continue;
        }
        BeanDefinitionBuilder delegate = BeanDefinitionBuilder.genericBeanDefinition(ResourceDatabasePopulator.class);
        delegate.addPropertyValue("ignoreFailedDrops", ignoreFailedDrops);
        delegate.addPropertyValue("continueOnError", continueOnError);
        // Use a factory bean for the resources so they can be given an order if a pattern is used
        BeanDefinitionBuilder resourcesFactory = BeanDefinitionBuilder.genericBeanDefinition(SortedResourcesFactoryBean.class);
        resourcesFactory.addConstructorArgValue(new TypedStringValue(scriptElement.getAttribute("location")));
        delegate.addPropertyValue("scripts", resourcesFactory.getBeanDefinition());
        if (StringUtils.hasLength(scriptElement.getAttribute("encoding"))) {
            delegate.addPropertyValue("sqlScriptEncoding", new TypedStringValue(scriptElement.getAttribute("encoding")));
        }
        String separator = getSeparator(element, scriptElement);
        if (separator != null) {
            delegate.addPropertyValue("separator", new TypedStringValue(separator));
        }
        delegates.add(delegate.getBeanDefinition());
    }
    builder.addPropertyValue("populators", delegates);
    return builder.getBeanDefinition();
}
Also used : BeanMetadataElement(org.springframework.beans.BeanMetadataElement) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BeanMetadataElement(org.springframework.beans.BeanMetadataElement) Element(org.w3c.dom.Element) ManagedList(org.springframework.beans.factory.support.ManagedList) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue)

Example 24 with TypedStringValue

use of org.springframework.beans.factory.config.TypedStringValue in project motan by weibocom.

the class MotanBeanDefinitionParser method parse.

@SuppressWarnings({ "rawtypes", "unchecked" })
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) throws ClassNotFoundException {
    RootBeanDefinition bd = new RootBeanDefinition();
    bd.setBeanClass(beanClass);
    // 不允许lazy init
    bd.setLazyInit(false);
    // 如果没有id则按照规则生成一个id,注册id到context中
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = element.getAttribute("class");
        }
        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, bd);
    }
    bd.getPropertyValues().addPropertyValue("id", id);
    if (ProtocolConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.protocolDefineNames.add(id);
    } else if (RegistryConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.registryDefineNames.add(id);
    } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicServiceConfigDefineNames.add(id);
    } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicRefererConfigDefineNames.add(id);
    } else if (ServiceConfigBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(Class.forName(className, true, Thread.currentThread().getContextClassLoader()));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            bd.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    }
    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    // 把配置文件中的可以set的属性放到bd中
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        // 必须是setXXX
        if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers()) || setter.getParameterTypes().length != 1) {
            continue;
        }
        String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-");
        props.add(property);
        if ("id".equals(property)) {
            bd.getPropertyValues().addPropertyValue("id", id);
            continue;
        }
        String value = element.getAttribute(property);
        if ("methods".equals(property)) {
            parseMethods(id, element.getChildNodes(), bd, parserContext);
        }
        if (StringUtils.isBlank(value)) {
            continue;
        }
        value = value.trim();
        if (value.length() == 0) {
            continue;
        }
        Object reference;
        if ("ref".equals(property)) {
            if (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);
        } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) {
            if (!value.contains(",")) {
                reference = new RuntimeBeanReference(value);
            } else {
                parseMultiRef("protocols", value, bd, parserContext);
                reference = null;
            }
        } else if ("registry".equals(property)) {
            parseMultiRef("registries", value, bd, parserContext);
            reference = null;
        } else if ("basicService".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else if ("basicReferer".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else if ("extConfig".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else {
            reference = new TypedStringValue(value);
        }
        if (reference != null) {
            bd.getPropertyValues().addPropertyValue(property, reference);
        }
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        // 把剩余的属性放到protocol的parameters里面
        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));
            }
        }
        bd.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return bd;
}
Also used : RegistryConfig(com.weibo.api.motan.config.RegistryConfig) BasicRefererInterfaceConfig(com.weibo.api.motan.config.BasicRefererInterfaceConfig) NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) ManagedMap(org.springframework.beans.factory.support.ManagedMap) HashSet(java.util.HashSet)

Aggregations

TypedStringValue (org.springframework.beans.factory.config.TypedStringValue)24 Element (org.w3c.dom.Element)9 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)7 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)6 ManagedMap (org.springframework.beans.factory.support.ManagedMap)6 Test (org.junit.Test)5 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)5 Node (org.w3c.dom.Node)5 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)4 Method (java.lang.reflect.Method)3 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)3 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 Mockito (org.mockito.Mockito)2 PropertyValue (org.springframework.beans.PropertyValue)2 BeanCreationException (org.springframework.beans.factory.BeanCreationException)2 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)2 ManagedList (org.springframework.beans.factory.support.ManagedList)2 NamedNodeMap (org.w3c.dom.NamedNodeMap)2