Example usage for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBeanDefinition

List of usage examples for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBeanDefinition

Introduction

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

Prototype

BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

Source Link

Document

Return the registered BeanDefinition for the specified bean, allowing access to its property values and constructor argument value (which can be modified during bean factory post-processing).

Usage

From source file:lodsve.core.condition.BeanTypeRegistry.java

private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
        throws Exception {
    if (definition instanceof AnnotatedBeanDefinition) {
        MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition)
                .getFactoryMethodMetadata();
        if (factoryMethodMetadata instanceof StandardMethodMetadata) {
            return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod();
        }// w  w  w .  j av  a 2  s.c om
    }
    BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName());
    Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(),
            beanFactory.getBeanClassLoader());
    return ReflectionUtils.findMethod(factoryClass, definition.getFactoryMethodName());
}

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)));
    }//www. j  av a 2  s .c om
    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.bigtester.ate.model.data.CaseDataProcessor.java

/**
 * {@inheritDoc}/*from  ww  w  . j a v a 2  s  . c  o m*/
 */
@Override
public void postProcessBeanFactory(@Nullable ConfigurableListableBeanFactory beanFactory)
        throws BeansException {
    if (beanFactory == null)
        throw new IllegalStateException("Spring Container initialization error");
    String[] homePageNames = beanFactory.getBeanNamesForType(Homepage.class, true, false);
    String[] lastPageNames = beanFactory.getBeanNamesForType(Lastpage.class, true, false);
    String[] regularPageNames = beanFactory.getBeanNamesForType(RegularPage.class, true, false);

    allPageNames = ArrayUtils.addAll(homePageNames, lastPageNames);
    allPageNames = ArrayUtils.addAll(allPageNames, regularPageNames);

    for (int i = 0; i < getAllPageNames().length; i++) {
        pageBeanDefs.add(beanFactory.getBeanDefinition(getAllPageNames()[i]));
    }

    for (int j = 0; j < pageBeanDefs.size(); j++) {
        if (null != pageBeanDefs.get(j).getPropertyValues()
                .getPropertyValue(XsdElementConstants.ATTR_BASEPAGEOBJECT_DATAFILE)) {
            caseDataFiles.add(new FileSystemResource((String) pageBeanDefs.get(j).getPropertyValues()
                    .getPropertyValue(XsdElementConstants.ATTR_BASEPAGEOBJECT_DATAFILE).getValue()));
        }
    }

    if (!caseDataFiles.isEmpty()) {
        dbInit = GlobalUtils.findDBInitializer(beanFactory);
        try {
            getDbInit().setInitXmlFiles(caseDataFiles);
        } catch (IOException e) {
            throw new BeanDefinitionValidationException("Page data file in page attribute can't be read!", e);
        }
        try {
            getDbInit().initialize(beanFactory);
        } catch (MalformedURLException | DatabaseUnitException | SQLException e) {
            throw new FatalBeanException("Case database creation error!", e);
        }
    }
}

From source file:com.bt.aloha.spring.BeanFactoryPostProcessorBase.java

protected void injectBeanIfDefined(ConfigurableListableBeanFactory beanFactory, String targetBeanName,
        String propertyName, Class<?> beanClassToInject) {
    String[] beanNamesForInjection = beanFactory.getBeanNamesForType(beanClassToInject);
    if (beanNamesForInjection != null && beanNamesForInjection.length > 0) {
        log.debug(String.format("Injecting bean %s into property %s of bean %s", beanClassToInject.getName(),
                propertyName, targetBeanName));
        if (beanNamesForInjection.length > 1)
            log.debug(String.format("Multiple beans of type %s found, injecting only the first one into %s",
                    beanClassToInject.getName(), targetBeanName));
        PropertyValue propertyValue = new PropertyValue(propertyName,
                new RuntimeBeanReference(beanNamesForInjection[0]));
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(targetBeanName);
        beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
    } else//  ww w .j a  v  a 2 s. c o  m
        log.info(String.format("Property %s not set for bean %s", propertyName, targetBeanName));
}

From source file:com.photon.phresco.configuration.XmlPropertyPlaceholderConfigurer.java

@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
        throws BeansException {

    org.springframework.util.StringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(
            props);/*w  w  w . j a  v a 2 s  . c om*/
    org.springframework.beans.factory.config.BeanDefinitionVisitor visitor = new org.springframework.beans.factory.config.BeanDefinitionVisitor(
            valueResolver);

    String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
    for (int i = 0; i < beanNames.length; i++) {
        // Check that we're not parsing our own bean definition,
        // to avoid failing on unresolvable placeholders in properties file locations.
        if (!(beanNames[i].equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
            BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]);
            try {
                visitor.visitBeanDefinition(bd);
            } catch (BeanDefinitionStoreException ex) {
                throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i],
                        ex.getMessage());
            }
        }
    }

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

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");
    }//  www .  j a v  a2  s. c o m
    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:com.liferay.arkadiko.bean.AKBeanPostProcessor.java

/**
 * Post process bean factory./* ww  w .jav a2s.  c  o m*/
 *
 * @param beanFactory the bean factory
 * @throws BeansException the beans exception
 */
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    if (!(beanFactory instanceof DefaultListableBeanFactory)) {
        return;
    }

    DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;

    defaultListableBeanFactory.setInstantiationStrategy(this);

    AutowireCandidateResolver autowireCandidateResolver = defaultListableBeanFactory
            .getAutowireCandidateResolver();

    defaultListableBeanFactory
            .setAutowireCandidateResolver(new AKAutowireCandidateResolver(autowireCandidateResolver));

    for (String beanName : defaultListableBeanFactory.getBeanDefinitionNames()) {

        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

        if (!(beanDefinition instanceof AbstractBeanDefinition)) {
            continue;
        }

        String className = beanDefinition.getBeanClassName();

        if (className == null) {
            continue;
        }

        try {
            AKBeanDefinition akBeanDefinition = new AKBeanDefinition(this,
                    (AbstractBeanDefinition) beanDefinition, beanName, getServiceRegistry());

            defaultListableBeanFactory.removeBeanDefinition(beanName);

            defaultListableBeanFactory.registerBeanDefinition(beanName, akBeanDefinition);
        } catch (Exception e) {
            if (_log.isLoggable(Level.SEVERE)) {
                _log.log(Level.SEVERE, e.getMessage(), e);
            }
        }
    }
}

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  w ww . j  av a 2 s . c  om*/
            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
    }
}