Search in sources :

Example 1 with CannotLoadBeanClassException

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

the class PropertiesBeanDefinitionReader method registerBeanDefinition.

/**
	 * Get all property values, given a prefix (which will be stripped)
	 * and add the bean they define to the factory with the given name
	 * @param beanName name of the bean to define
	 * @param map Map containing string pairs
	 * @param prefix prefix of each entry, which will be stripped
	 * @param resourceDescription description of the resource that the
	 * Map came from (for logging purposes)
	 * @throws BeansException if the bean definition could not be parsed or registered
	 */
protected void registerBeanDefinition(String beanName, Map<?, ?> map, String prefix, String resourceDescription) throws BeansException {
    String className = null;
    String parent = null;
    String scope = GenericBeanDefinition.SCOPE_SINGLETON;
    boolean isAbstract = false;
    boolean lazyInit = false;
    ConstructorArgumentValues cas = new ConstructorArgumentValues();
    MutablePropertyValues pvs = new MutablePropertyValues();
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        String key = StringUtils.trimWhitespace((String) entry.getKey());
        if (key.startsWith(prefix + SEPARATOR)) {
            String property = key.substring(prefix.length() + SEPARATOR.length());
            if (CLASS_KEY.equals(property)) {
                className = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (PARENT_KEY.equals(property)) {
                parent = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (ABSTRACT_KEY.equals(property)) {
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                isAbstract = TRUE_VALUE.equals(val);
            } else if (SCOPE_KEY.equals(property)) {
                // Spring 2.0 style
                scope = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (SINGLETON_KEY.equals(property)) {
                // Spring 1.2 style
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                scope = ((val == null || TRUE_VALUE.equals(val) ? GenericBeanDefinition.SCOPE_SINGLETON : GenericBeanDefinition.SCOPE_PROTOTYPE));
            } else if (LAZY_INIT_KEY.equals(property)) {
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                lazyInit = TRUE_VALUE.equals(val);
            } else if (property.startsWith(CONSTRUCTOR_ARG_PREFIX)) {
                if (property.endsWith(REF_SUFFIX)) {
                    int index = Integer.parseInt(property.substring(1, property.length() - REF_SUFFIX.length()));
                    cas.addIndexedArgumentValue(index, new RuntimeBeanReference(entry.getValue().toString()));
                } else {
                    int index = Integer.parseInt(property.substring(1));
                    cas.addIndexedArgumentValue(index, readValue(entry));
                }
            } else if (property.endsWith(REF_SUFFIX)) {
                // This isn't a real property, but a reference to another prototype
                // Extract property name: property is of form dog(ref)
                property = property.substring(0, property.length() - REF_SUFFIX.length());
                String ref = StringUtils.trimWhitespace((String) entry.getValue());
                // It doesn't matter if the referenced bean hasn't yet been registered:
                // this will ensure that the reference is resolved at runtime.
                Object val = new RuntimeBeanReference(ref);
                pvs.add(property, val);
            } else {
                // It's a normal bean property.
                pvs.add(property, readValue(entry));
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Registering bean definition for bean name '" + beanName + "' with " + pvs);
    }
    // backwards compatibility reasons.
    if (parent == null && className == null && !beanName.equals(this.defaultParentBean)) {
        parent = this.defaultParentBean;
    }
    try {
        AbstractBeanDefinition bd = BeanDefinitionReaderUtils.createBeanDefinition(parent, className, getBeanClassLoader());
        bd.setScope(scope);
        bd.setAbstract(isAbstract);
        bd.setLazyInit(lazyInit);
        bd.setConstructorArgumentValues(cas);
        bd.setPropertyValues(pvs);
        getRegistry().registerBeanDefinition(beanName, bd);
    } catch (ClassNotFoundException ex) {
        throw new CannotLoadBeanClassException(resourceDescription, beanName, className, ex);
    } catch (LinkageError err) {
        throw new CannotLoadBeanClassException(resourceDescription, beanName, className, err);
    }
}
Also used : ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with CannotLoadBeanClassException

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

the class XmlBeanFactoryTests method testClassNotFoundWithDefaultBeanClassLoader.

/**
	 * When using a BeanFactory. singletons are of course not pre-instantiated.
	 * So rubbish class names in bean defs must now not be 'resolved' when the
	 * bean def is being parsed, 'cos everything on a bean def is now lazy, but
	 * must rather only be picked up when the bean is instantiated.
	 */
@Test
public void testClassNotFoundWithDefaultBeanClassLoader() {
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    new XmlBeanDefinitionReader(factory).loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT);
    // cool, no errors, so the rubbish class name in the bean def was not resolved
    try {
        // let's resolve the bean definition; must blow up
        factory.getBean("classNotFound");
        fail("Must have thrown a CannotLoadBeanClassException");
    } catch (CannotLoadBeanClassException ex) {
        assertTrue(ex.getResourceDescription().indexOf("classNotFound.xml") != -1);
        assertTrue(ex.getCause() instanceof ClassNotFoundException);
    }
}
Also used : CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) Test(org.junit.Test)

Example 3 with CannotLoadBeanClassException

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

the class AbstractJaxWsServiceExporter method publishEndpoints.

/**
	 * Publish all {@link javax.jws.WebService} annotated beans in the
	 * containing BeanFactory.
	 * @see #publishEndpoint
	 */
public void publishEndpoints() {
    Set<String> beanNames = new LinkedHashSet<>(this.beanFactory.getBeanDefinitionCount());
    beanNames.addAll(Arrays.asList(this.beanFactory.getBeanDefinitionNames()));
    if (this.beanFactory instanceof ConfigurableBeanFactory) {
        beanNames.addAll(Arrays.asList(((ConfigurableBeanFactory) this.beanFactory).getSingletonNames()));
    }
    for (String beanName : beanNames) {
        try {
            Class<?> type = this.beanFactory.getType(beanName);
            if (type != null && !type.isInterface()) {
                WebService wsAnnotation = type.getAnnotation(WebService.class);
                WebServiceProvider wsProviderAnnotation = type.getAnnotation(WebServiceProvider.class);
                if (wsAnnotation != null || wsProviderAnnotation != null) {
                    Endpoint endpoint = createEndpoint(this.beanFactory.getBean(beanName));
                    if (this.endpointProperties != null) {
                        endpoint.setProperties(this.endpointProperties);
                    }
                    if (this.executor != null) {
                        endpoint.setExecutor(this.executor);
                    }
                    if (wsAnnotation != null) {
                        publishEndpoint(endpoint, wsAnnotation);
                    } else {
                        publishEndpoint(endpoint, wsProviderAnnotation);
                    }
                    this.publishedEndpoints.add(endpoint);
                }
            }
        } catch (CannotLoadBeanClassException ex) {
        // ignore beans where the class is not resolvable
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) WebServiceProvider(javax.xml.ws.WebServiceProvider) Endpoint(javax.xml.ws.Endpoint) WebService(javax.jws.WebService) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException)

Example 4 with CannotLoadBeanClassException

use of org.springframework.beans.factory.CannotLoadBeanClassException in project spring-boot by spring-projects.

the class BeanTypeRegistry method addBeanTypeForNonAliasDefinition.

private void addBeanTypeForNonAliasDefinition(String name) {
    try {
        String factoryName = BeanFactory.FACTORY_BEAN_PREFIX + name;
        RootBeanDefinition beanDefinition = (RootBeanDefinition) this.beanFactory.getMergedBeanDefinition(name);
        if (!beanDefinition.isAbstract() && !requiresEagerInit(beanDefinition.getFactoryBeanName())) {
            if (this.beanFactory.isFactoryBean(factoryName)) {
                Class<?> factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, beanDefinition, name);
                this.beanTypes.put(name, factoryBeanGeneric);
                this.beanTypes.put(factoryName, this.beanFactory.getType(factoryName));
            } else {
                this.beanTypes.put(name, this.beanFactory.getType(name));
            }
        }
    } catch (CannotLoadBeanClassException ex) {
        // Probably contains a placeholder
        logIgnoredError("bean class loading failure for bean", name, ex);
    } catch (BeanDefinitionStoreException ex) {
        // Probably contains a placeholder
        logIgnoredError("unresolvable metadata in bean definition", name, ex);
    }
}
Also used : BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition)

Example 5 with CannotLoadBeanClassException

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

the class DefaultListableBeanFactory method doGetBeanNamesForType.

private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
    List<String> result = new ArrayList<>();
    // Check all bean definitions.
    for (String beanName : this.beanDefinitionNames) {
        // is not defined as alias for some other bean.
        if (!isAlias(beanName)) {
            try {
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                // Only check bean definition if it is complete.
                if (!mbd.isAbstract() && (allowEagerInit || ((mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading())) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) {
                    // In case of FactoryBean, match object created by FactoryBean.
                    boolean isFactoryBean = isFactoryBean(beanName, mbd);
                    BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
                    boolean matchFound = (allowEagerInit || !isFactoryBean || (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) && (includeNonSingletons || (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) && isTypeMatch(beanName, type);
                    if (!matchFound && isFactoryBean) {
                        // In case of FactoryBean, try to match FactoryBean instance itself next.
                        beanName = FACTORY_BEAN_PREFIX + beanName;
                        matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
                    }
                    if (matchFound) {
                        result.add(beanName);
                    }
                }
            } catch (CannotLoadBeanClassException ex) {
                if (allowEagerInit) {
                    throw ex;
                }
                // Probably contains a placeholder: let's ignore it for type matching purposes.
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
                }
                onSuppressedException(ex);
            } catch (BeanDefinitionStoreException ex) {
                if (allowEagerInit) {
                    throw ex;
                }
                // Probably contains a placeholder: let's ignore it for type matching purposes.
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
                }
                onSuppressedException(ex);
            }
        }
    }
    // Check manually registered singletons too.
    for (String beanName : this.manualSingletonNames) {
        try {
            // In case of FactoryBean, match object created by FactoryBean.
            if (isFactoryBean(beanName)) {
                if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
                    result.add(beanName);
                    // Match found for this bean: do not match FactoryBean itself anymore.
                    continue;
                }
                // In case of FactoryBean, try to match FactoryBean itself next.
                beanName = FACTORY_BEAN_PREFIX + beanName;
            }
            // Match raw bean instance (might be raw FactoryBean).
            if (isTypeMatch(beanName, type)) {
                result.add(beanName);
            }
        } catch (NoSuchBeanDefinitionException ex) {
            // Shouldn't happen - probably a result of circular reference resolution...
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to check manually registered singleton with name '" + beanName + "'", ex);
            }
        }
    }
    return StringUtils.toStringArray(result);
}
Also used : BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) ArrayList(java.util.ArrayList) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Aggregations

CannotLoadBeanClassException (org.springframework.beans.factory.CannotLoadBeanClassException)5 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)2 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 Map (java.util.Map)1 WebService (javax.jws.WebService)1 Endpoint (javax.xml.ws.Endpoint)1 WebServiceProvider (javax.xml.ws.WebServiceProvider)1 Test (org.junit.Test)1 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)1 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)1 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)1 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)1 ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)1 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)1 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)1 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)1