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:de.acosix.alfresco.utility.common.spring.ImplementationClassReplacingBeanFactoryPostProcessor.java

protected void applyChange(final Function<String, BeanDefinition> getBeanDefinition) {
    final BeanDefinition beanDefinition = getBeanDefinition.apply(this.targetBeanName);
    if (beanDefinition != null) {
        if (this.originalClassName == null
                || this.originalClassName.equals(beanDefinition.getBeanClassName())) {
            LOGGER.debug("[{}] Patching implementation class Spring bean {} to {}", this.beanName,
                    this.targetBeanName, this.replacementClassName);
            beanDefinition.setBeanClassName(this.replacementClassName);
        } else {/* w  w  w . j  a v  a2  s.  com*/
            LOGGER.info(
                    "[{}] patch will not be applied - class of bean {} does not match expected implementation {}",
                    this.beanName, this.targetBeanName, this.originalClassName);
        }
    } else {
        LOGGER.info("[{}] patch cannot be applied - no bean with name {} has been defined", this.beanName,
                this.targetBeanName);
    }
}

From source file:com.newtranx.util.cassandra.spring.MapperScannerConfigurer.java

@SuppressWarnings("unused") // compiler bug?
@Override/*from   ww  w .  j ava 2s. c  o m*/
public void postProcessBeanFactory(ConfigurableListableBeanFactory context) throws BeansException {
    synchronized (lock) {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Table.class));
        for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {
            Class<?> entityCls;
            try {
                entityCls = Class.forName(bd.getBeanClassName());
            } catch (ClassNotFoundException e) {
                throw new AssertionError(e);
            }
            log.info("Creating proxy mapper for entity: " + entityCls.getName());
            CassandraMapper annotation = entityCls.getAnnotation(CassandraMapper.class);
            Mapper<?> bean = createProxy(Mapper.class, new MyInterceptor(entityCls, annotation.singleton()));
            String beanName;
            if (annotation == null)
                beanName = StringUtils.uncapitalize(entityCls.getSimpleName()) + "Mapper";
            else
                beanName = annotation.value();
            context.registerSingleton(beanName, bean);
            log.info("Bean registed, name=" + beanName + ", bean=" + bean.toString());
        }
    }
}

From source file:org.bytesoft.bytetcc.supports.zk.TransactionCuratorClient.java

public void initZookeeperAddressIfNecessary(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] beanNameArray = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        if (com.alibaba.dubbo.config.RegistryConfig.class.getName().equals(beanDef.getBeanClassName())) {
            MutablePropertyValues mpv = beanDef.getPropertyValues();
            PropertyValue protpv = mpv.getPropertyValue(KEY_DUBBO_REGISTRY_PROTOCOL);
            PropertyValue addrpv = mpv.getPropertyValue(KEY_DUBBO_REGISTRY_ADDRESS);

            String protocol = null;
            String address = null;
            if (addrpv == null) {
                throw new FatalBeanException("zookeeper address cannot be null!"); // should never happen
            } else if (protpv == null) {
                String value = String.valueOf(addrpv.getValue());
                try {
                    URL url = new URL(null, value, this);
                    protocol = url.getProtocol();
                    address = url.getAuthority();
                } catch (Exception ex) {
                    throw new FatalBeanException("Unsupported format!");
                }//w w  w.j  a  v  a2 s  . c o m
            } else {
                protocol = String.valueOf(protpv.getValue());
                String value = StringUtils.trimToEmpty(String.valueOf(addrpv.getValue()));
                int index = value.indexOf(protocol);
                if (index == -1) {
                    address = value;
                } else if (index == 0) {
                    String str = StringUtils.trimToEmpty(value.substring(protocol.length()));
                    if (str.startsWith("://")) {
                        address = StringUtils.trimToEmpty(str.substring(3));
                    } else {
                        throw new FatalBeanException("Unsupported format!");
                    }
                } else {
                    throw new FatalBeanException("Unsupported format!");
                }
            }

            if (KEY_DUBBO_REGISTRY_ZOOKEEPER.equalsIgnoreCase(protocol) == false) {
                throw new FatalBeanException("Unsupported protocol!");
            }

            String addrKey = "zookeeperAddr";
            String[] watcherBeanArray = beanFactory
                    .getBeanNamesForType(org.bytesoft.bytetcc.supports.zk.TransactionCuratorClient.class);
            BeanDefinition watcherBeanDef = beanFactory.getBeanDefinition(watcherBeanArray[0]);
            MutablePropertyValues warcherMpv = watcherBeanDef.getPropertyValues();
            PropertyValue warcherPv = warcherMpv.getPropertyValue(addrKey);
            if (warcherPv == null) {
                warcherMpv.addPropertyValue(new PropertyValue(addrKey, address));
            } else {
                warcherMpv.removePropertyValue(addrKey);
                warcherMpv.addPropertyValue(new PropertyValue(addrKey, address));
            }

        }
    }
}

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

public void convert() throws Exception {
    addImport("com.google.inject.AbstractModule");
    addImport("com.google.inject.Provides");

    PrintWriter writer = createOutputFileWriter();
    try {/*from   w w w .ja  v a 2s.co  m*/
        ModuleGenerator generator = new ModuleGenerator(this, writer);
        String[] names = beanFactory.getBeanDefinitionNames();
        for (String name : names) {
            BeanDefinition definition = beanFactory.getBeanDefinition(name);
            String className = definition.getBeanClassName();
            if (ignoreClasses.contains(className)) {
                continue;
            }

            generateBeanDefinition(generator, name, definition, className);
        }
        generator.generate();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:com.sourceallies.beanoh.spring.wrapper.BeanohApplicationContext.java

/**
 * This will fail if there are duplicate beans in the Spring context. Beans
 * that are configured in the bootstrap context will not be considered
 * duplicate beans./*from  w w  w  .jav a 2  s  .c  o  m*/
 */
public void assertUniqueBeans(Set<String> ignoredDuplicateBeanNames) {
    for (BeanohBeanFactoryMethodInterceptor callback : callbacks) {
        Map<String, List<BeanDefinition>> beanDefinitionMap = callback.getBeanDefinitionMap();
        for (String key : beanDefinitionMap.keySet()) {
            if (!ignoredDuplicateBeanNames.contains(key)) {
                List<BeanDefinition> definitions = beanDefinitionMap.get(key);
                List<String> resourceDescriptions = new ArrayList<String>();
                for (BeanDefinition definition : definitions) {
                    String resourceDescription = definition.getResourceDescription();
                    if (resourceDescription == null) {
                        resourceDescriptions.add(definition.getBeanClassName());
                    } else if (!resourceDescription.endsWith("-BeanohContext.xml]")) {
                        if (!resourceDescriptions.contains(resourceDescription)) {
                            resourceDescriptions.add(resourceDescription);
                        }
                    }
                }
                if (resourceDescriptions.size() > 1) {
                    throw new DuplicateBeanDefinitionException("Bean '" + key + "' was defined "
                            + resourceDescriptions.size() + " times.\n"
                            + "Either remove duplicate bean definitions or ignore them with the 'ignoredDuplicateBeanNames' method.\n"
                            + "Configuration locations:" + messageUtil.list(resourceDescriptions));
                }
            }
        }
    }
}

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

@SuppressWarnings("unchecked")
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory)
        throws BeansException {

    if (!(configurableListableBeanFactory instanceof DefaultListableBeanFactory)) {
        throw new IllegalStateException(
                "EnvironmentAnnotationConfigurer needs to operate on a DefaultListableBeanFactory");
    }/*from  w ww  .  j a  va 2s . c om*/
    DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
    defaultListableBeanFactory.setAutowireCandidateResolver(new ConstrettoAutowireCandidateResolver());
    String[] beanNames = configurableListableBeanFactory.getBeanDefinitionNames();
    int lowestDiscoveredPriority = Integer.MAX_VALUE;
    for (String beanName : beanNames) {
        BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName);
        if (beanDefinition.getBeanClassName() != null) {
            try {
                Class beanClass = Class.forName(beanDefinition.getBeanClassName());
                Environment environmentAnnotation = findEnvironmentAnnotation(beanClass);
                if (environmentAnnotation != null) {
                    if (!assemblyContextResolver.getAssemblyContext().isEmpty()) {
                        boolean autowireCandidate = decideIfAutowireCandiate(beanName, environmentAnnotation);
                        beanDefinition.setAutowireCandidate(autowireCandidate);
                        if (autowireCandidate) {
                            removeNonAnnotatedBeansFromAutowireForType(beanClass,
                                    configurableListableBeanFactory);
                        }
                    } else {
                        beanDefinition.setAutowireCandidate(false);
                    }
                }
            } catch (ClassNotFoundException e) {
                beanDefinition.setAutowireCandidate(false);
            }
        }
    }
}

From source file:org.openmrs.module.kenyacore.calculation.CalculationManager.java

/**
 * @see org.openmrs.module.kenyacore.ContentManager#refresh()
 *///from  w  w w. j  av  a 2 s .c  o m
@Override
public synchronized void refresh() {
    calculationClasses.clear();
    flagCalculationClasses.clear();

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AssignableTypeFilter(PatientCalculation.class));

    for (BeanDefinition bd : scanner.findCandidateComponents("org.openmrs.module")) {
        try {
            Class<? extends PatientCalculation> clazz = (Class<? extends PatientCalculation>) Context
                    .loadClass(bd.getBeanClassName());
            calculationClasses.put(bd.getBeanClassName(), clazz);

            if (PatientFlagCalculation.class.isAssignableFrom(clazz)) {
                flagCalculationClasses.add((Class<? extends PatientFlagCalculation>) clazz);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        log.debug("Registered calculation class " + bd.getBeanClassName());
    }
}

From source file:net.paoding.rose.jade.context.spring.JadeBeanFactoryPostProcessor.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String postProcessor = System.getProperty("jade.spring.postProcessor");
    if ("disable".equals(postProcessor)) {
        logger.info("jade.spring.postProcessor: disable");
        return;/* w w w .j  ava  2  s.c  om*/
    } else if (postProcessor == null || "enable".equals(postProcessor)) {
        logger.info("jade.spring.postProcessor: enable");
    } else {
        throw new IllegalArgumentException(//
                "illegal property of 'jade.spring.postProcessor': " + postProcessor);
    }
    if (logger.isInfoEnabled()) {
        logger.info("[jade] starting ...");
    }
    final List<ResourceRef> resources;
    try {
        // scope
        resources = RoseScanner.getInstance().getJarOrClassesFolderResources();
    } catch (IOException e) {
        throw new ApplicationContextException("error on getJarResources/getClassesFolderResources", e);
    }
    List<String> urls = new LinkedList<String>();
    for (ResourceRef ref : resources) {
        if (ref.hasModifier("dao") || ref.hasModifier("DAO")) {
            try {
                Resource resource = ref.getResource();
                File resourceFile = resource.getFile();
                if (resourceFile.isFile()) {
                    urls.add("jar:file:" + resourceFile.toURI().getPath() + ResourceUtils.JAR_URL_SEPARATOR);
                } else if (resourceFile.isDirectory()) {
                    urls.add(resourceFile.toURI().toString());
                }
            } catch (IOException e) {
                throw new ApplicationContextException("error on resource.getFile", e);
            }
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("[jade] found " + urls.size() + " jade urls: " + urls);
    }
    if (urls.size() > 0) {
        DAOComponentProvider provider = new DAOComponentProvider(true);
        if (filters != null) {
            for (TypeFilter excludeFilter : filters) {
                provider.addExcludeFilter(excludeFilter);
            }
        }

        Set<String> daoClassNames = new HashSet<String>();

        for (String url : urls) {
            if (logger.isInfoEnabled()) {
                logger.info("[jade] call 'jade/find'");
            }
            Set<BeanDefinition> dfs = provider.findCandidateComponents(url);
            if (logger.isInfoEnabled()) {
                logger.info("[jade] found " + dfs.size() + " beanDefinition from '" + url + "'");
            }
            for (BeanDefinition beanDefinition : dfs) {
                String daoClassName = beanDefinition.getBeanClassName();

                if (isDisable(daoClassName)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "[jade] ignored disabled jade dao class: " + daoClassName + "  [" + url + "]");
                    }
                    continue;
                }

                if (daoClassNames.contains(daoClassName)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[jade] ignored replicated jade dao class: " + daoClassName + "  [" + url
                                + "]");
                    }
                    continue;
                }
                daoClassNames.add(daoClassName);

                MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
                propertyValues.addPropertyValue("DAOClass", daoClassName);
                ScannedGenericBeanDefinition scannedBeanDefinition = (ScannedGenericBeanDefinition) beanDefinition;
                scannedBeanDefinition.setPropertyValues(propertyValues);
                scannedBeanDefinition.setBeanClass(DAOFactoryBean.class);

                DefaultListableBeanFactory defaultBeanFactory = (DefaultListableBeanFactory) beanFactory;
                defaultBeanFactory.registerBeanDefinition(daoClassName, beanDefinition);

                if (logger.isDebugEnabled()) {
                    logger.debug("[jade] register DAO: " + daoClassName);
                }
            }
        }
    }
    if (logger.isInfoEnabled()) {
        logger.info("[jade] exits");
    }
}

From source file:org.nuunframework.spring.SpringModule.java

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

    ConfigurableListableBeanFactory currentBeanFactory = this.beanFactory;
    do {//w w  w  .ja  va2  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 : this.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:net.phoenix.thrift.xml.ProcessorBeanDefinitionParser.java

/**
 * context-scan???Iface/* w w  w. j av a 2s .  c o m*/
 * serviceparserContext?serviceprocesor
 */
private Map<String, BeanDefinition> scanProcessors(ParserContext parserContext) {
    Map<String, BeanDefinition> processors = new HashMap<String, BeanDefinition>();
    for (String serviceName : parserContext.getRegistry().getBeanDefinitionNames()) {
        BeanDefinition serviceBeanDefinition = parserContext.getRegistry().getBeanDefinition(serviceName);
        Class<?> clazz;
        try {
            clazz = Class.forName(serviceBeanDefinition.getBeanClassName());
        } catch (ClassNotFoundException e) {
            throw new CannotLoadBeanClassException(parserContext.getReaderContext().getResource().getFilename(),
                    serviceName, serviceBeanDefinition.getBeanClassName(), e);
        }
        Processor annotation = AnnotationUtils.findAnnotation(clazz, Processor.class);
        if (annotation != null) {
            //processor class;
            Class<?> processorClass = annotation.processor();
            // build bean definition for processor;
            BeanDefinition processorBeanDefinition = this.createProcessorBean(processorClass, serviceName);
            processors.put(serviceName, processorBeanDefinition);
        }
    }
    return processors;
}