Example usage for org.springframework.beans.factory.config BeanDefinition isSingleton

List of usage examples for org.springframework.beans.factory.config BeanDefinition isSingleton

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config BeanDefinition isSingleton.

Prototype

boolean isSingleton();

Source Link

Document

Return whether this a Singleton, with a single, shared instance returned on all calls.

Usage

From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass,
        boolean required) throws ClassNotFoundException {
    RootBeanDefinition bd = new RootBeanDefinition();
    bd.setBeanClass(beanClass);//www. j  a va  2  s  . co m
    // ??lazy init
    bd.setLazyInit(false);

    // id?id,idcontext
    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;
    // ??setbd
    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)) {
        // protocolparameters?
        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;
}

From source file:com.agileapes.motorex.cli.value.impl.SpringValueReaderContext.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    final String[] names = beanFactory.getBeanDefinitionNames();
    for (String name : names) {
        final BeanDefinition definition = beanFactory.getBeanDefinition(name);
        if (definition.isSingleton()) {
            final String className = definition.getBeanClassName();
            try {
                final Class<?> beanType = ClassUtils.forName(className, beanFactory.getBeanClassLoader());
                if (ValueReader.class.isAssignableFrom(beanType)) {
                    register(beanFactory.getBean(name, ValueReader.class));
                }/*from   w ww .  j  a  v a 2s. c  om*/
            } catch (ClassNotFoundException e) {
                throw new BeanCreationNotAllowedException(name, "Failed to access bean");
            }
        }
    }
}

From source file:com.agileapes.motorex.cli.target.impl.SpringExecutionTargetContext.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    final String[] names = beanFactory.getBeanDefinitionNames();
    for (String name : names) {
        final BeanDefinition definition = beanFactory.getBeanDefinition(name);
        if (definition.isSingleton()) {
            final String className = definition.getBeanClassName();
            try {
                final Class<?> beanClass = ClassUtils.forName(className, beanFactory.getBeanClassLoader());
                if (ExecutionTarget.class.isAssignableFrom(beanClass)) {
                    final ExecutionTarget target = beanFactory.getBean(name, ExecutionTarget.class);
                    if (target instanceof AbstractIdentifiedExecutionTarget) {
                        AbstractIdentifiedExecutionTarget executionTarget = (AbstractIdentifiedExecutionTarget) target;
                        executionTarget.setIdentifier(name);
                    }//from w  w  w. j av a2s  .c  o  m
                    register(target);
                }
            } catch (ClassNotFoundException e) {
                throw new BeanCreationException(name, "Could not access bean class");
            }
        }
    }
}

From source file:org.brekka.stillingar.spring.pc.ConfigurationPlaceholderConfigurer.java

/**
 * Copied in its entirety from the {@link PropertyPlaceholderConfigurer} method of the same name. The only changes
 * are to the valueResolver and BeanDefinitionVisitor instances.
 *//*from   w  w  w. ja  va2 s  .c om*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactoryToProcess) throws BeansException {

    String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
    for (String curName : beanNames) {
        CustomStringValueResolver valueResolver = new CustomStringValueResolver(this.placeholderParser,
                this.configurationSource, this.beanFactory);

        // Check that we're not parsing our own bean definition,
        // to avoid failing on unresolvable placeholders in properties file
        // locations.
        if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
            BeanDefinition beanDef = beanFactoryToProcess.getBeanDefinition(curName);
            try {
                BeanDefinitionVisitor visitor = new CustomBeanDefinitionVisitor(curName, beanDef.isSingleton(),
                        valueResolver);
                visitor.visitBeanDefinition(beanDef);
            } catch (Exception ex) {
                throw new BeanDefinitionStoreException(beanDef.getResourceDescription(), curName, ex);
            }
        }
    }

    StringValueResolver valueResolver = new CustomStringValueResolver(this.placeholderParser,
            this.configurationSource, this.beanFactory);

    // New in Spring 2.5: resolve placeholders in alias target names and
    // aliases as well.
    beanFactoryToProcess.resolveAliases(valueResolver);

    // New in Spring 3.0: resolve placeholders in embedded values such as
    // annotation attributes.
    beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
}

From source file:com.mtgi.analytics.aop.config.v11.BtDataSourceBeanDefinitionDecorator.java

public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
    BeanDefinition delegate = definition.getBeanDefinition();
    BeanDefinitionBuilder wrapper = BeanDefinitionBuilder.rootBeanDefinition(DataSourceFactory.class);
    wrapper.addPropertyReference("trackingManager", node.getNodeValue());
    wrapper.addPropertyValue("targetDataSource", delegate);
    wrapper.addPropertyValue("singleton", delegate.isSingleton());
    return new BeanDefinitionHolder(wrapper.getRawBeanDefinition(), definition.getBeanName());
}

From source file:com.arondor.common.reflection.parser.spring.XMLBeanDefinitionParser.java

private ObjectConfiguration parseBeanDefinition(BeanDefinition beanDefinition) {
    LOGGER.debug("Resource description : " + beanDefinition.getResourceDescription());
    ObjectConfiguration objectConfiguration = objectConfigurationFactory.createObjectConfiguration();
    objectConfiguration.setClassName(hashHelper.hashClassName(beanDefinition.getBeanClassName()));
    objectConfiguration.setSingleton(beanDefinition.isSingleton());

    Map<String, ElementConfiguration> fields = new LinkedHashMap<String, ElementConfiguration>();
    objectConfiguration.setFields(fields);

    for (PropertyValue ppt : beanDefinition.getPropertyValues().getPropertyValueList()) {
        try {//from w w  w.  j  ava  2  s. co  m
            ElementConfiguration fieldConfiguration = beanPropertyParser.parseProperty(ppt.getValue());
            fields.put(hashHelper.hashFieldName(beanDefinition.getBeanClassName(), ppt.getName()),
                    fieldConfiguration);
        } catch (Exception e) {
            LOGGER.error("The value " + ppt.getValue() + " of property " + ppt + " cannot be parsed", e);
        }
    }

    List<ElementConfiguration> constructorArguments = new ArrayList<ElementConfiguration>();
    objectConfiguration.setConstructorArguments(constructorArguments);
    for (ValueHolder va : beanDefinition.getConstructorArgumentValues().getGenericArgumentValues()) {
        ElementConfiguration constructorAgrument = beanPropertyParser.parseProperty(va.getValue());
        constructorArguments.add(constructorAgrument);
    }
    return objectConfiguration;
}

From source file:org.iff.infra.util.spring.script.ScriptFactoryPostProcessor.java

@Override
public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
    // We only apply special treatment to ScriptFactory implementations here.
    if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
        return null;
    }//ww  w .ja  v  a  2s. c o  m

    BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);

    try {
        String scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
        String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
        prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);

        ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName,
                ScriptFactory.class);
        ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName,
                scriptFactory.getScriptSourceLocator());
        Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

        Class<?> scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
        if (scriptedType != null) {
            return scriptedType;
        } else if (!ObjectUtils.isEmpty(interfaces)) {
            return (interfaces.length == 1 ? interfaces[0] : createCompositeInterface(interfaces));
        } else {
            if (bd.isSingleton()) {
                Object bean = this.scriptBeanFactory.getBean(scriptedObjectBeanName);
                if (bean != null) {
                    return bean.getClass();
                }
            }
        }
    } catch (Exception ex) {
        if (ex instanceof BeanCreationException && ((BeanCreationException) ex)
                .getMostSpecificCause() instanceof BeanCurrentlyInCreationException) {
            if (logger.isTraceEnabled()) {
                logger.trace("Could not determine scripted object type for bean '" + beanName + "': "
                        + ex.getMessage());
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not determine scripted object type for bean '" + beanName + "'", ex);
            }
        }
    }

    return null;
}

From source file:org.impalaframework.spring.ProxyCreatingBeanFactory.java

@Override
public void preInstantiateSingletons() throws BeansException {
    if (logger.isInfoEnabled()) {
        logger.info("Pre-instantiating singletons in factory [" + this + "]");
    }/*from  www  .j  a  va2s .co m*/

    String[] beanNames = this.getBeanDefinitionNames();

    for (int i = 0; i < beanNames.length; i++) {
        String beanName = beanNames[i];
        if (!containsSingleton(beanName) && containsBeanDefinition(beanName)) {

            BeanDefinition bd = getMergedBeanDefinition(beanName);
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {

                if (bd instanceof RootBeanDefinition) {
                    RootBeanDefinition rootBeanDefinition = (RootBeanDefinition) bd;

                    Class<?> beanClass = resolveBeanClass(rootBeanDefinition, beanName);
                    if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
                        getBean(FACTORY_BEAN_PREFIX + beanName);
                    } else {
                        getBean(beanName);
                    }
                } else {
                    log.warn("Unable to instantiate bean definition " + bd + " as this is not an instance of "
                            + RootBeanDefinition.class.getName());
                }
            }
        }
    }
}

From source file:org.impalaframework.spring.service.SpringServiceBeanUtils.java

/**
 * Checks that the bean with given name contained in the specified bean factory is a singleton.
 * Will return true if bean represented by a bean registered under the scope <code>singletone</code>.
 * If the bean is also a factory bean (see {@link FactoryBean}), then the {@link FactoryBean}
 * instance also needs to be a singleton.
 * /*  ww  w.  j a  va  2s .c  o  m*/
 * Note that in order to work properly the {@link BeanFactory} must be able to recover the {@link BeanDefinition}
 * for a particular bean name. This in particular must mean implementing {@link BeanDefinitionRegistry} or 
 * {@link BeanDefinitionExposing}. In the latter case, if null is returned, then the bean will be treated as a singleton.
 * 
 * @return true if bean is singleton registered bean and, if applicable, a singleton {@link FactoryBean}.
 */
public static boolean isSingleton(BeanFactory beanFactory, String beanName) {

    Assert.notNull(beanFactory, "beanFactory cannot be null");
    Assert.notNull(beanName, "beanName cannot be null");

    boolean singleton = true;

    boolean isBeanFactory = beanFactory.containsBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName);
    if (isBeanFactory) {
        FactoryBean<?> factoryBean = (FactoryBean<?>) beanFactory
                .getBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName);
        singleton = factoryBean.isSingleton();
    }

    if (singleton) {
        //ApplicationContext implements this implements this
        ListableBeanFactory registry = (ListableBeanFactory) beanFactory;

        //we're only interested in top level definitions
        //inner beans won't appear here, so 
        boolean containsBeanDefinition = registry.containsBeanDefinition(beanName);
        if (containsBeanDefinition) {
            BeanDefinition beanDefinition = getBeanDefinition(registry, beanName);

            if (beanDefinition != null) {
                singleton = beanDefinition.isSingleton();
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot check whether bean definition " + beanName
                        + " is singleton as it is not available as a top level bean");
            }
        }
    }
    return singleton;
}

From source file:org.springframework.richclient.application.ProgressMonitoringBeanFactoryPostProcessor.java

/**
 * Notifies this instance's associated progress monitor of progress made
 * while processing the given bean factory.
 * //  w w w .ja  va  2  s .c  o  m
 * @param beanFactory the bean factory that is to be processed.
 */
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {

    if (beanFactory == null) {
        return;
    }

    String[] beanNames = beanFactory.getBeanDefinitionNames();
    int singletonBeanCount = 0;

    for (int i = 0; i < beanNames.length; i++) {
        // using beanDefinition to check singleton property because when
        // accessing through
        // context (applicationContext.isSingleton(beanName)), bean will be
        // created already,
        // possibly bypassing other BeanFactoryPostProcessors
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanNames[i]);

        if (beanDefinition.isSingleton()) {
            singletonBeanCount++;
        }

    }

    this.progressMonitor.taskStarted(this.loadingAppContextMessage, singletonBeanCount);

    beanFactory.addBeanPostProcessor(new ProgressMonitoringBeanPostProcessor(beanFactory));

}