Search in sources :

Example 56 with NoSuchBeanDefinitionException

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

the class BeanFactoryAnnotationUtils method isQualifierMatch.

/**
	 * Check whether the named bean declares a qualifier of the given name.
	 * @param qualifier the qualifier to match
	 * @param beanName the name of the candidate bean
	 * @param beanFactory the {@code BeanFactory} from which to retrieve the named bean
	 * @return {@code true} if either the bean definition (in the XML case)
	 * or the bean's factory method (in the {@code @Bean} case) defines a matching
	 * qualifier value (through {@code <qualifier>} or {@code @Qualifier})
	 * @since 5.0
	 */
public static boolean isQualifierMatch(Predicate<String> qualifier, String beanName, BeanFactory beanFactory) {
    // Try quick bean name or alias match first...
    if (qualifier.test(beanName)) {
        return true;
    }
    if (beanFactory != null) {
        for (String alias : beanFactory.getAliases(beanName)) {
            if (qualifier.test(alias)) {
                return true;
            }
        }
        try {
            if (beanFactory instanceof ConfigurableBeanFactory) {
                BeanDefinition bd = ((ConfigurableBeanFactory) beanFactory).getMergedBeanDefinition(beanName);
                // Explicit qualifier metadata on bean definition? (typically in XML definition)
                if (bd instanceof AbstractBeanDefinition) {
                    AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
                    AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName());
                    if (candidate != null) {
                        Object value = candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY);
                        if (value != null && qualifier.test(value.toString())) {
                            return true;
                        }
                    }
                }
                // Corresponding qualifier on factory method? (typically in configuration class)
                if (bd instanceof RootBeanDefinition) {
                    Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod();
                    if (factoryMethod != null) {
                        Qualifier targetAnnotation = AnnotationUtils.getAnnotation(factoryMethod, Qualifier.class);
                        if (targetAnnotation != null) {
                            return qualifier.test(targetAnnotation.value());
                        }
                    }
                }
            }
            // Corresponding qualifier on bean implementation class? (for custom user types)
            Class<?> beanType = beanFactory.getType(beanName);
            if (beanType != null) {
                Qualifier targetAnnotation = AnnotationUtils.getAnnotation(beanType, Qualifier.class);
                if (targetAnnotation != null) {
                    return qualifier.test(targetAnnotation.value());
                }
            }
        } catch (NoSuchBeanDefinitionException ex) {
        // Ignore - can't compare qualifiers for a manually registered singleton object
        }
    }
    return false;
}
Also used : ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AutowireCandidateQualifier(org.springframework.beans.factory.support.AutowireCandidateQualifier) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) AutowireCandidateQualifier(org.springframework.beans.factory.support.AutowireCandidateQualifier)

Example 57 with NoSuchBeanDefinitionException

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

the class BeanFactoryAnnotationUtils method qualifiedBeanOfType.

/**
	 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
	 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
	 * @param bf the BeanFactory to get the target bean from
	 * @param beanType the type of bean to retrieve
	 * @param qualifier the qualifier for selecting between multiple bean matches
	 * @return the matching bean of type {@code T} (never {@code null})
	 */
private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) {
    String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
    String matchingBean = null;
    for (String beanName : candidateBeans) {
        if (isQualifierMatch(qualifier::equals, beanName, bf)) {
            if (matchingBean != null) {
                throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
            }
            matchingBean = beanName;
        }
    }
    if (matchingBean != null) {
        return bf.getBean(matchingBean, beanType);
    } else if (bf.containsBean(qualifier)) {
        // Fallback: target bean at least found by bean name - probably a manually registered singleton.
        return bf.getBean(qualifier, beanType);
    } else {
        throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
    }
}
Also used : NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) NoUniqueBeanDefinitionException(org.springframework.beans.factory.NoUniqueBeanDefinitionException)

Example 58 with NoSuchBeanDefinitionException

use of org.springframework.beans.factory.NoSuchBeanDefinitionException 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)

Example 59 with NoSuchBeanDefinitionException

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

the class AbstractBeanFactory method getMergedBeanDefinition.

/**
	 * Return a RootBeanDefinition for the given bean, by merging with the
	 * parent if the given bean's definition is a child bean definition.
	 * @param beanName the name of the bean definition
	 * @param bd the original bean definition (Root/ChildBeanDefinition)
	 * @param containingBd the containing bean definition in case of inner bean,
	 * or {@code null} in case of a top-level bean
	 * @return a (potentially merged) RootBeanDefinition for the given bean
	 * @throws BeanDefinitionStoreException in case of an invalid bean definition
	 */
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd, BeanDefinition containingBd) throws BeanDefinitionStoreException {
    synchronized (this.mergedBeanDefinitions) {
        RootBeanDefinition mbd = null;
        // Check with full lock now in order to enforce the same merged instance.
        if (containingBd == null) {
            mbd = this.mergedBeanDefinitions.get(beanName);
        }
        if (mbd == null) {
            if (bd.getParentName() == null) {
                // Use copy of given root bean definition.
                if (bd instanceof RootBeanDefinition) {
                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                } else {
                    mbd = new RootBeanDefinition(bd);
                }
            } else {
                // Child bean definition: needs to be merged with parent.
                BeanDefinition pbd;
                try {
                    String parentBeanName = transformedBeanName(bd.getParentName());
                    if (!beanName.equals(parentBeanName)) {
                        pbd = getMergedBeanDefinition(parentBeanName);
                    } else {
                        BeanFactory parent = getParentBeanFactory();
                        if (parent instanceof ConfigurableBeanFactory) {
                            pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
                        } else {
                            throw new NoSuchBeanDefinitionException(parentBeanName, "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent");
                        }
                    }
                } catch (NoSuchBeanDefinitionException ex) {
                    throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
                }
                // Deep copy with overridden values.
                mbd = new RootBeanDefinition(pbd);
                mbd.overrideFrom(bd);
            }
            // Set default singleton scope, if not configured before.
            if (!StringUtils.hasLength(mbd.getScope())) {
                mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
            }
            // definition will not have inherited the merged outer bean's singleton status.
            if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                mbd.setScope(containingBd.getScope());
            }
            // instance of the bean, or at least have already created an instance before.
            if (containingBd == null && isCacheBeanMetadata()) {
                this.mergedBeanDefinitions.put(beanName, mbd);
            }
        }
        return mbd;
    }
}
Also used : ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Example 60 with NoSuchBeanDefinitionException

use of org.springframework.beans.factory.NoSuchBeanDefinitionException in project midpoint by Evolveum.

the class Initializer method init.

public void init(OperationResult result) throws TaskManagerInitializationException {
    MidpointConfiguration midpointConfiguration = taskManager.getMidpointConfiguration();
    LOGGER.info("Task Manager initialization.");
    // get the configuration (general section + JDBC section as well)
    TaskManagerConfiguration configuration = taskManager.getConfiguration();
    configuration.checkAllowedKeys(midpointConfiguration);
    configuration.setBasicInformation(midpointConfiguration);
    configuration.validateBasicInformation();
    LOGGER.info("Task Manager: Quartz Job Store: " + (configuration.isJdbcJobStore() ? "JDBC" : "in-memory") + ", " + (configuration.isClustered() ? "" : "NOT ") + "clustered. Threads: " + configuration.getThreads());
    if (configuration.isJdbcJobStore()) {
        // quartz properties related to database connection will be taken from SQL repository
        String defaultJdbcUrlPrefix = null;
        SqlRepositoryConfiguration sqlConfig = null;
        try {
            SqlRepositoryFactory sqlRepositoryFactory = (SqlRepositoryFactory) taskManager.getBeanFactory().getBean("sqlRepositoryFactory");
            sqlConfig = sqlRepositoryFactory.getSqlConfiguration();
            if (sqlConfig.isEmbedded()) {
                defaultJdbcUrlPrefix = sqlRepositoryFactory.prepareJdbcUrlPrefix(sqlConfig);
            }
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.info("SqlRepositoryFactory is not available, JDBC Job Store configuration will be taken from taskManager section only.");
            LOGGER.trace("Reason is", e);
        } catch (RepositoryServiceFactoryException e) {
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot determine default JDBC URL for embedded database", e);
        }
        configuration.setJdbcJobStoreInformation(midpointConfiguration, sqlConfig, defaultJdbcUrlPrefix);
        configuration.validateJdbcJobStoreInformation();
    }
    // register node
    // may throw initialization exception
    taskManager.getClusterManager().createNodeObject(result);
    if (!taskManager.getConfiguration().isTestMode()) {
        // in test mode do not start cluster manager thread nor verify cluster config
        // does not throw exceptions, sets the ERROR state if necessary, however
        taskManager.getClusterManager().checkClusterConfiguration(result);
    }
    NoOpTaskHandler.instantiateAndRegister(taskManager);
    WaitForSubtasksByPollingTaskHandler.instantiateAndRegister(taskManager);
    WaitForTasksTaskHandler.instantiateAndRegister(taskManager);
    // unfortunately, there seems to be no clean way of letting jobs know the taskManager
    JobExecutor.setTaskManagerQuartzImpl(taskManager);
    // the same here
    JobStarter.setTaskManagerQuartzImpl(taskManager);
    taskManager.getExecutionManager().initializeLocalScheduler();
    if (taskManager.getLocalNodeErrorStatus() != NodeErrorStatusType.OK) {
        taskManager.getExecutionManager().shutdownLocalSchedulerChecked();
    }
    // populate the scheduler with jobs (if RAM-based), or synchronize with midPoint repo
    if (taskManager.getExecutionManager().synchronizeJobStores(result) == false) {
        if (!configuration.isJdbcJobStore()) {
            LOGGER.error("Some or all tasks could not be imported from midPoint repository to Quartz job store. They will therefore not be executed.");
        } else {
            LOGGER.warn("Some or all tasks could not be synchronized between midPoint repository and Quartz job store. They may not function correctly.");
        }
    }
    LOGGER.trace("Quartz scheduler initialized (not yet started, however)");
    LOGGER.info("Task Manager initialized");
}
Also used : MidpointConfiguration(com.evolveum.midpoint.common.configuration.api.MidpointConfiguration) SqlRepositoryFactory(com.evolveum.midpoint.repo.sql.SqlRepositoryFactory) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) RepositoryServiceFactoryException(com.evolveum.midpoint.repo.api.RepositoryServiceFactoryException) SqlRepositoryConfiguration(com.evolveum.midpoint.repo.sql.SqlRepositoryConfiguration)

Aggregations

NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)71 Test (org.junit.Test)27 BeanCreationException (org.springframework.beans.factory.BeanCreationException)18 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)15 ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)14 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)9 HashMap (java.util.HashMap)8 EventBus (org.apache.cloudstack.framework.events.EventBus)8 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)8 SimpleDateFormat (java.text.SimpleDateFormat)7 Date (java.util.Date)7 EventBusException (org.apache.cloudstack.framework.events.EventBusException)7 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)7 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)6 Method (java.lang.reflect.Method)5 BeanFactory (org.springframework.beans.factory.BeanFactory)5 ConfigurableListableBeanFactory (org.springframework.beans.factory.config.ConfigurableListableBeanFactory)5 ApplicationContext (org.springframework.context.ApplicationContext)5 ArrayList (java.util.ArrayList)4 Account (com.cloud.user.Account)3