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

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

Introduction

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

Prototype

@Nullable
String getBeanClassName();

Source Link

Document

Return the current bean class name of this bean definition.

Usage

From source file:org.guicerecipes.spring.converter.SpringConverter.java

protected void addChildBeanDefinition(ModuleGenerator generator, ProduceMethod method, String name,
        PropertyValue propertyValue, BeanDefinition beanDefinition) {
    String childBeanName = childBeanName(name, propertyValue.getName());
    String childType = addImport(beanDefinition.getBeanClassName());
    String expression = addParameter(method, childType, childBeanName);
    generateBeanDefinition(generator, childBeanName, beanDefinition, childType);
    method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
}

From source file:io.nuun.plugin.spring.SpringModule.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void bindFromApplicationContext() {
    boolean debugEnabled = logger.isDebugEnabled();

    ConfigurableListableBeanFactory currentBeanFactory = beanFactory;
    do {/* w  ww  .j  a v  a2 s .  c  o m*/
        for (String beanName : currentBeanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = currentBeanFactory.getMergedBeanDefinition(beanName);
            if (!beanDefinition.isAbstract()) {
                Class<?> beanClass = classFromString(beanDefinition.getBeanClassName());
                if (beanClass == null) {
                    logger.warn("Cannot bind spring bean " + beanName + " because its class "
                            + beanDefinition.getBeanClassName() + " failed to load");
                    return;
                }

                SpringBeanDefinition springBeanDefinition = new SpringBeanDefinition(beanName,
                        currentBeanFactory);

                // Adding bean with its base type
                addBeanDefinition(beanClass, springBeanDefinition);

                // Adding bean with its parent type if enabled
                Class<?> parentClass = beanClass.getSuperclass();
                if (parentClass != null && parentClass != Object.class) {
                    addBeanDefinition(parentClass, springBeanDefinition);
                }

                // Adding bean with its immediate interfaces if enabled
                for (Class<?> i : beanClass.getInterfaces()) {
                    addBeanDefinition(i, springBeanDefinition);
                }
            }
        }
        BeanFactory factory = currentBeanFactory.getParentBeanFactory();
        if (factory != null) {
            if (factory instanceof ConfigurableListableBeanFactory) {
                currentBeanFactory = (ConfigurableListableBeanFactory) factory;
            } else {
                logger.info(
                        "Cannot go up further in the bean factory hierarchy, parent bean factory doesn't implement ConfigurableListableBeanFactory");
                currentBeanFactory = null;
            }
        } else {
            currentBeanFactory = null;
        }
    } while (currentBeanFactory != null);

    for (Map.Entry<Class<?>, Map<String, SpringBeanDefinition>> entry : beanDefinitions.entrySet()) {
        Class<?> type = entry.getKey();
        Map<String, SpringBeanDefinition> definitions = entry.getValue();

        // Bind by name for each bean of this type and by type if there is no ambiguity
        for (SpringBeanDefinition candidate : definitions.values()) {
            if (debugEnabled) {
                logger.info("Binding spring bean " + candidate.getName() + " by name and type "
                        + type.getCanonicalName());
            }

            bind(type).annotatedWith(Names.named(candidate.getName())).toProvider(
                    new ByNameSpringContextProvider(type, candidate.getName(), candidate.getBeanFactory()));
        }
    }
}

From source file:org.codehaus.griffon.runtime.spring.GriffonRuntimeConfigurator.java

private void doPostResourceConfiguration(GriffonApplication application,
        RuntimeSpringConfiguration springConfig) {
    ClassLoader classLoader = ApplicationClassLoader.get();
    String resourceName = SPRING_RESOURCES_XML;
    try {//from   w w  w  . j av a  2 s .  c om
        Resource springResources = new ClassPathResource(resourceName);

        if (springResources != null && springResources.exists()) {
            if (LOG.isDebugEnabled())
                LOG.debug(
                        "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL());
            DefaultListableBeanFactory xmlBf = new DefaultListableBeanFactory();
            new XmlBeanDefinitionReader(xmlBf).loadBeanDefinitions(springResources);
            xmlBf.setBeanClassLoader(classLoader);
            String[] beanNames = xmlBf.getBeanDefinitionNames();
            if (LOG.isDebugEnabled())
                LOG.debug("[RuntimeConfiguration] Found [" + beanNames.length + "] beans to configure");
            for (String beanName : beanNames) {
                BeanDefinition bd = xmlBf.getBeanDefinition(beanName);
                final String beanClassName = bd.getBeanClassName();
                Class<?> beanClass = beanClassName == null ? null
                        : ClassUtils.forName(beanClassName, classLoader);

                springConfig.addBeanDefinition(beanName, bd);
                String[] aliases = xmlBf.getAliases(beanName);
                for (String alias : aliases) {
                    springConfig.addAlias(alias, beanName);
                }
                if (beanClass != null) {
                    if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass)) {
                        ((ConfigurableApplicationContext) springConfig.getUnrefreshedApplicationContext())
                                .addBeanFactoryPostProcessor(
                                        (BeanFactoryPostProcessor) xmlBf.getBean(beanName));
                    }
                }
            }
        } else if (LOG.isDebugEnabled()) {
            LOG.debug("[RuntimeConfiguration] " + resourceName + " not found. Skipping configuration.");
        }
    } catch (Exception ex) {
        LOG.error("[RuntimeConfiguration] Unable to perform post initialization config: " + resourceName,
                sanitize(ex));
    }

    loadSpringGroovyResources(springConfig, application);
}

From source file:org.constretto.spring.EnvironmentAnnotationConfigurer.java

@SuppressWarnings("unchecked")
private void removeNonAnnotatedBeansFromAutowireForType(Class lookupClass,
        ConfigurableListableBeanFactory configurableListableBeanFactory) throws ClassNotFoundException {
    List<String> beanNames = new ArrayList<String>();
    Class[] interfaces = lookupClass.getInterfaces();
    for (Class anInterface : interfaces) {
        beanNames.addAll(asList(BeanFactoryUtils
                .beanNamesForTypeIncludingAncestors(configurableListableBeanFactory, anInterface)));
    }//from w  w w. j  a  va  2s .com
    List<BeanDefinition> potentialMatches = new ArrayList<BeanDefinition>();
    for (String beanName : beanNames) {
        BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
        Class beanClass = Class.forName(beanDefinition.getBeanClassName());
        beanDefinition.setAttribute(INCLUDE_IN_COLLECTIONS, beanClass.getInterfaces());
        Environment environmentAnnotation = findEnvironmentAnnotation(beanClass);
        if (environmentAnnotation == null) {
            beanDefinition.setAutowireCandidate(false);
        } else {
            potentialMatches.add(beanDefinition);
        }
    }
    if (potentialMatches.size() == 1) {
        potentialMatches.get(0).setAutowireCandidate(true);
    } else {
        List<BeanDefinition> highestPriorityBeans = new ArrayList<BeanDefinition>();
        for (BeanDefinition potentialMatch : potentialMatches) {
            if (potentialMatch.isAutowireCandidate()) {
                potentialMatch.setAutowireCandidate(false);
                highestPriorityBeans = prioritizeBeans(potentialMatch, highestPriorityBeans);
            }
        }
        if (highestPriorityBeans.size() == 1) {
            highestPriorityBeans.get(0).setAutowireCandidate(true);
        } else {
            List<String> equalPriorityBeans = new ArrayList<String>();
            for (BeanDefinition highestPriorityBean : highestPriorityBeans) {
                equalPriorityBeans.add(highestPriorityBean.getBeanClassName());
            }
            throw new ConstrettoException("More than one bean with the class or interface + ["
                    + lookupClass.getSimpleName()
                    + "] registered with same tag. Could not resolve priority. To fix this, remove one of the following beans "
                    + equalPriorityBeans.toString());
        }
    }
}

From source file:org.springmodules.cache.config.CachingListenerValidatorImpl.java

/**
 * Resolves class of a beanDefinition//from w  w w .jav a2s.co  m
 * @param beanDefinition the bean definition
 * @return class of the bean definition
 * @throws IllegalStateException if the given bean definition class can not
 * be resolved
 * @see org.springframework.beans.factory.config.BeanDefinition#setBeanClassName(String)
 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#resolveBeanClass(ClassLoader)
 */
protected Class resolveBeanClass(BeanDefinition beanDefinition) throws IllegalStateException {
    try {
        return ((AbstractBeanDefinition) beanDefinition).resolveBeanClass(ClassUtils.getDefaultClassLoader());
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
                "Could not resolve class [" + beanDefinition.getBeanClassName() + "] of caching listener");
    }
}

From source file:gov.nih.nci.cabig.ctms.tools.spring.BeanNameControllerUrlResolver.java

protected ResolvedControllerReference createResolvedReference(String controllerName,
        ConfigurableListableBeanFactory beanFactory) {
    if (log.isDebugEnabled())
        log.debug("Resolving URL for controller " + controllerName);
    BeanDefinition def = beanFactory.getBeanDefinition(controllerName);
    String url = resolveUrl(controllerName, beanFactory);
    if (url != null) {
        if (log.isDebugEnabled())
            log.debug("URL for " + controllerName + " is " + url);
        return new ResolvedControllerReference(controllerName, def.getBeanClassName(), servletName, url);
    } else {/* ww  w.ja va 2 s  .co m*/
        log.warn("Could not find a URL mapping for controller bean " + controllerName);
        return null;
    }
}

From source file:org.solmix.runtime.support.spring.SpringConfigurer.java

private void initWildcardDefinitionMap() {
    if (null != appContexts) {
        for (ApplicationContext appContext : appContexts) {
            for (String n : appContext.getBeanDefinitionNames()) {
                if (isWildcardBeanName(n)) {
                    AutowireCapableBeanFactory bf = appContext.getAutowireCapableBeanFactory();
                    BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) bf;
                    BeanDefinition bd = bdr.getBeanDefinition(n);
                    String className = bd.getBeanClassName();
                    if (null != className) {
                        String orig = n;
                        if (n.charAt(0) == '*') {
                            //old wildcard
                            n = "." + n.replaceAll("\\.", "\\.");
                        }/*from   w w  w  . j  a v a  2s  .  c o m*/
                        try {
                            Matcher matcher = Pattern.compile(n).matcher("");
                            List<MatcherHolder> m = wildCardBeanDefinitions.get(className);
                            if (m == null) {
                                m = new ArrayList<MatcherHolder>();
                                wildCardBeanDefinitions.put(className, m);
                            }
                            MatcherHolder holder = new MatcherHolder(orig, matcher);
                            m.add(holder);
                        } catch (PatternSyntaxException npe) {
                            //not a valid patter, we'll ignore
                        }
                    } else {
                        LOG.warn("Wildcars with not class {}", n);
                    }
                }
            }
        }
    }
}

From source file:org.bytesoft.bytetcc.supports.dubbo.DubboConfigPostProcessor.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    List<BeanDefinition> appNameList = new ArrayList<BeanDefinition>();
    List<BeanDefinition> providerList = new ArrayList<BeanDefinition>();
    List<BeanDefinition> consumerList = new ArrayList<BeanDefinition>();
    List<BeanDefinition> protocolList = new ArrayList<BeanDefinition>();
    List<BeanDefinition> registryList = new ArrayList<BeanDefinition>();

    Map<String, BeanDefinition> serviceMap = new HashMap<String, BeanDefinition>();
    Map<String, BeanDefinition> referenceMap = new HashMap<String, BeanDefinition>();

    Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
    Map<String, BeanDefinition> compensableMap = new HashMap<String, BeanDefinition>();

    String[] beanNameArray = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        Class<?> beanClass = null;
        try {/*from ww w.j  a v  a  2s. c o  m*/
            beanClass = cl.loadClass(beanClassName);
        } catch (Exception ex) {
            logger.warn("Cannot load class {}, beanId= {}!", beanClassName, beanName, ex);
            continue;
        }

        clazzMap.put(beanClassName, beanClass);

        if (beanClass.getAnnotation(Compensable.class) != null) {
            compensableMap.put(beanName, beanDef);
        }
    }

    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        Class<?> beanClass = clazzMap.get(beanClassName);

        if (com.alibaba.dubbo.config.ApplicationConfig.class.equals(beanClass)) {
            appNameList.add(beanDef);
        } else if (com.alibaba.dubbo.config.ProtocolConfig.class.equals(beanClass)) {
            protocolList.add(beanDef);
        } else if (com.alibaba.dubbo.config.RegistryConfig.class.equals(beanClass)) {
            registryList.add(beanDef);
        } else if (com.alibaba.dubbo.config.ProviderConfig.class.equals(beanClass)) {
            providerList.add(beanDef);
        } else if (com.alibaba.dubbo.config.ConsumerConfig.class.equals(beanClass)) {
            consumerList.add(beanDef);
        } else if (com.alibaba.dubbo.config.spring.ServiceBean.class.equals(beanClass)) {
            MutablePropertyValues mpv = beanDef.getPropertyValues();
            PropertyValue ref = mpv.getPropertyValue("ref");
            RuntimeBeanReference beanRef = (RuntimeBeanReference) ref.getValue();
            String refBeanName = beanRef.getBeanName();
            if (compensableMap.containsKey(refBeanName) == false) {
                continue;
            }

            serviceMap.put(beanName, beanDef);
        } else if (com.alibaba.dubbo.config.spring.ReferenceBean.class.equals(beanClass)) {
            MutablePropertyValues mpv = beanDef.getPropertyValues();
            PropertyValue group = mpv.getPropertyValue("group");
            if (group == null || group.getValue() == null
                    || "org.bytesoft.bytetcc".equals(group.getValue()) == false) {
                continue;
            }

            referenceMap.put(beanName, beanDef);
        }
    }

    Set<BeanDefinition> providerSet = new HashSet<BeanDefinition>();
    Set<BeanDefinition> protocolSet = new HashSet<BeanDefinition>();
    for (Iterator<Map.Entry<String, BeanDefinition>> itr = serviceMap.entrySet().iterator(); itr.hasNext();) {
        Map.Entry<String, BeanDefinition> entry = itr.next();
        BeanDefinition beanDef = entry.getValue();
        MutablePropertyValues mpv = beanDef.getPropertyValues();
        PropertyValue provider = mpv.getPropertyValue("provider");
        PropertyValue protocol = mpv.getPropertyValue("protocol");

        String providerValue = provider == null ? null : String.valueOf(provider.getValue());
        if (providerValue == null) {
            if (providerList.size() > 0) {
                providerSet.add(providerList.get(0));
            }
        } else if ("N/A".equals(providerValue) == false) {
            String[] keyArray = providerValue.split("\\s*,\\s*");
            for (int j = 0; j < keyArray.length; j++) {
                String key = keyArray[j];
                BeanDefinition def = beanFactory.getBeanDefinition(key);
                providerSet.add(def);
            }
        }

        String protocolValue = protocol == null ? null : String.valueOf(protocol.getValue());
        if (protocolValue == null) {
            if (protocolList.size() > 0) {
                protocolSet.add(protocolList.get(0));
            }
        } else if ("N/A".equals(protocolValue) == false) {
            String[] keyArray = protocolValue.split("\\s*,\\s*");
            for (int i = 0; i < keyArray.length; i++) {
                String key = keyArray[i];
                BeanDefinition def = beanFactory.getBeanDefinition(key);
                protocolSet.add(def);
            }
        }
    }

    ApplicationConfigValidator appConfigValidator = new ApplicationConfigValidator();
    appConfigValidator.setDefinitionList(appNameList);
    appConfigValidator.validate();

    if (protocolList.size() == 0) {
        throw new FatalBeanException("There is no protocol config specified!");
    }

    for (Iterator<BeanDefinition> itr = protocolSet.iterator(); itr.hasNext();) {
        BeanDefinition beanDef = itr.next();
        ProtocolConfigValidator validator = new ProtocolConfigValidator();
        validator.setBeanDefinition(beanDef);
        validator.validate();
    }

    for (Iterator<BeanDefinition> itr = providerSet.iterator(); itr.hasNext();) {
        BeanDefinition beanDef = itr.next();
        ProviderConfigValidator validator = new ProviderConfigValidator();
        validator.setBeanDefinition(beanDef);
        validator.validate();
    }

    for (Iterator<Map.Entry<String, BeanDefinition>> itr = serviceMap.entrySet().iterator(); itr.hasNext();) {
        Map.Entry<String, BeanDefinition> entry = itr.next();
        ServiceConfigValidator validator = new ServiceConfigValidator();
        validator.setBeanName(entry.getKey());
        validator.setBeanDefinition(entry.getValue());
        validator.validate(); // retries, loadbalance, cluster, filter, group
    }

    for (Iterator<Map.Entry<String, BeanDefinition>> itr = referenceMap.entrySet().iterator(); itr.hasNext();) {
        Map.Entry<String, BeanDefinition> entry = itr.next();
        ReferenceConfigValidator validator = new ReferenceConfigValidator();
        validator.setBeanName(entry.getKey());
        validator.setBeanDefinition(entry.getValue());
        validator.validate(); // retries, loadbalance, cluster, filter
    }
}