Example usage for org.springframework.beans.factory UnsatisfiedDependencyException UnsatisfiedDependencyException

List of usage examples for org.springframework.beans.factory UnsatisfiedDependencyException UnsatisfiedDependencyException

Introduction

In this page you can find the example usage for org.springframework.beans.factory UnsatisfiedDependencyException UnsatisfiedDependencyException.

Prototype

public UnsatisfiedDependencyException(@Nullable String resourceDescription, @Nullable String beanName,
        @Nullable InjectionPoint injectionPoint, BeansException ex) 

Source Link

Document

Create a new UnsatisfiedDependencyException.

Usage

From source file:com.yy.kunka.core.workflow.processor.BaseProcessor.java

/**
 * Called after the properties have been set, Ensures the list of activities
 * is not empty and each activity is supported by this Workflow Processor.
 *
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 *///from   w  w  w .  j a  va  2 s  . c  om
@Override
public void afterPropertiesSet() throws Exception {

    if (!(beanFactory instanceof ListableBeanFactory)) {
        throw new BeanInitializationException("The workflow processor [" + beanName + "] "
                + "is not managed by a ListableBeanFactory, please re-deploy using some derivative of ListableBeanFactory such as"
                + "ClassPathXmlApplicationContext ");
    }

    if (CollectionUtils.isEmpty(activities) && !isAllowEmptyActivities()) {
        throw new UnsatisfiedDependencyException(getBeanDesc(), beanName, "activities",
                "No activities were wired for this workflow");
    }

    //sort the activities based on their configured order
    OrderComparator.sort(activities);
}

From source file:org.broadleafcommerce.core.workflow.BaseProcessor.java

/**
 * Called after the properties have been set, Ensures the list of activities
 *  is not empty and each activity is supported by this Workflow Processor
 *
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 *///from  w w w.  j a  va  2 s  .  co m
@Override
public void afterPropertiesSet() throws Exception {

    if (!(beanFactory instanceof ListableBeanFactory)) {
        throw new BeanInitializationException("The workflow processor [" + beanName + "] "
                + "is not managed by a ListableBeanFactory, please re-deploy using some derivative of ListableBeanFactory such as"
                + "ClassPathXmlApplicationContext ");
    }

    if (CollectionUtils.isEmpty(activities) && !isAllowEmptyActivities()) {
        throw new UnsatisfiedDependencyException(getBeanDesc(), beanName, "activities",
                "No activities were wired for this workflow");
    }

    //sort the activities based on their configured order
    OrderComparator.sort(activities);

    HashSet<String> moduleNames = new HashSet<String>();
    for (Iterator<Activity<ProcessContext<? extends Object>>> iter = activities.iterator(); iter.hasNext();) {
        Activity<? extends ProcessContext<? extends Object>> activity = iter.next();
        if (!supports(activity)) {
            throw new BeanInitializationException("The workflow processor [" + beanName + "] does "
                    + "not support the activity of type" + activity.getClass().getName());
        }

        if (activity instanceof ModuleActivity) {
            moduleActivities.add((ModuleActivity) activity);
            moduleNames.add(((ModuleActivity) activity).getModuleName());
        }
    }

    if (CollectionUtils.isNotEmpty(moduleActivities)) {
        //log the fact that we've got some modifications to the workflow
        StringBuffer message = new StringBuffer();
        message.append("The following modules have made changes to the " + getBeanName() + " workflow: ");
        message.append(Arrays.toString(moduleNames.toArray()));
        message.append("\n");
        message.append("The final ordering of activities for the " + getBeanName() + " workflow is: \n");
        ArrayList<String> activityNames = new ArrayList<String>();
        CollectionUtils.collect(activities, new Transformer() {

            @Override
            public Object transform(Object input) {
                return ((Activity) input).getBeanName();
            }
        }, activityNames);
        message.append(Arrays.toString(activityNames.toArray()));

        supportLogger.lifecycle(LifeCycleEvent.CONFIG, message.toString());
    }

}

From source file:org.gbif.portal.util.workflow.BaseActivity.java

/**
 * Called after the properties have been set, ensuring that only the workflow, or psWorkflowKey
 * have been used/*from   ww  w.  ja v  a2s  .co  m*/
 *
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
public void afterPropertiesSet() throws Exception {
    if (getWorkflow() != null && getPsWorkflowKey() != null) {
        throw new UnsatisfiedDependencyException("BaseActivity", beanName, "workflow/psWorkflowKey",
                "Only the workflow OR the psWorkflowKey may be used - NOT both");
    }
    if (getPsWorkflowKey() != null && (getPropertyStore() == null || getContextKeyPsNamespaces() == null)) {
        throw new UnsatisfiedDependencyException("BaseActivity", beanName, "propertyStore",
                "The property store must be wired, and the contextKeyPsNamespaces set when using the psWorkflowKey");
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Abstract method defining "autowire by type" (bean properties by type) behavior.
 * <p>This is like PicoContainer default, in which there must be exactly one bean
 * of the property type in the bean factory. This makes bean factories simple to
 * configure for small namespaces, but doesn't work as well as standard Spring
 * behavior for bigger applications./*from ww  w.java2 s. co  m*/
 * @param beanName the name of the bean to autowire by type
 * @param mbd the merged bean definition to update through autowiring
 * @param bw the BeanWrapper from which we can obtain information about the bean
 * @param pvs the PropertyValues to register wired objects with
 */
protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw,
        MutablePropertyValues pvs) {

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }

    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // Don't try autowiring by type for type Object: never makes sense,
            // even if it technically is a unsatisfied, non-simple property.
            if (Object.class != pd.getPropertyType()) {
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Autowiring by type from bean name '" + beanName + "' via property '"
                                + propertyName + "' to bean named '" + autowiredBeanName + "'");
                    }
                }
                autowiredBeanNames.clear();
            }
        } catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
        }
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Perform a dependency check that all properties exposed have been set,
 * if desired. Dependency checks can be objects (collaborating beans),
 * simple (primitives and String), or all (both).
 * @param beanName the name of the bean//from  w w w .  j a  va 2  s.  com
 * @param mbd the merged bean definition the bean was created with
 * @param pds the relevant property descriptors for the target bean
 * @param pvs the property values to be applied to the bean
 * @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor)
 */
protected void checkDependencies(String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds,
        @Nullable PropertyValues pvs) throws UnsatisfiedDependencyException {

    int dependencyCheck = mbd.getDependencyCheck();
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) {
            boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
            boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL)
                    || (isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE)
                    || (!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
            if (unsatisfied) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
                        "Set this property value or disable dependency checking for this bean.");
            }
        }
    }
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

/**
 * Create an array of arguments to invoke a constructor or factory method,
 * given the resolved constructor argument values.
 *//*from  w w  w  .  jav a 2s .c  o m*/
private ArgumentsHolder createArgumentArray(String beanName, RootBeanDefinition mbd,
        @Nullable ConstructorArgumentValues resolvedValues, BeanWrapper bw, Class<?>[] paramTypes,
        @Nullable String[] paramNames, Executable executable, boolean autowiring, boolean fallback)
        throws UnsatisfiedDependencyException {

    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);

    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);

    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        Class<?> paramType = paramTypes[paramIndex];
        String paramName = (paramNames != null ? paramNames[paramIndex] : "");
        // Try to find matching constructor argument value, either indexed or generic.
        ConstructorArgumentValues.ValueHolder valueHolder = null;
        if (resolvedValues != null) {
            valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
            // If we couldn't find a direct match and are not supposed to autowire,
            // let's try the next generic, untyped argument value as fallback:
            // it could match after type conversion (for example, String -> int).
            if (valueHolder == null
                    && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
                valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
            }
        }
        if (valueHolder != null) {
            // We found a potential match - let's give it a try.
            // Do not consider the same value definition multiple times!
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            if (valueHolder.isConverted()) {
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            } else {
                MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
                try {
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                } catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName,
                            new InjectionPoint(methodParam),
                            "Could not convert argument value of type ["
                                    + ObjectUtils.nullSafeClassName(valueHolder.getValue())
                                    + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
                Object sourceHolder = valueHolder.getSource();
                if (sourceHolder instanceof ConstructorArgumentValues.ValueHolder) {
                    Object sourceValue = ((ConstructorArgumentValues.ValueHolder) sourceHolder).getValue();
                    args.resolveNecessary = true;
                    args.preparedArguments[paramIndex] = sourceValue;
                }
            }
            args.arguments[paramIndex] = convertedValue;
            args.rawArguments[paramIndex] = originalValue;
        } else {
            MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
            // No explicit match found: we're either supposed to autowire or
            // have to fail creating an argument array for the given constructor.
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName,
                        new InjectionPoint(methodParam),
                        "Ambiguous argument values for parameter of type [" + paramType.getName()
                                + "] - did you specify the correct bean references as arguments?");
            }
            try {
                Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames,
                        converter, fallback);
                args.rawArguments[paramIndex] = autowiredArgument;
                args.arguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = new AutowiredArgumentMarker();
                args.resolveNecessary = true;
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName,
                        new InjectionPoint(methodParam), ex);
            }
        }
    }

    for (String autowiredBeanName : autowiredBeanNames) {
        this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (logger.isDebugEnabled()) {
            logger.debug("Autowiring by type from bean name '" + beanName + "' via "
                    + (executable instanceof Constructor ? "constructor" : "factory method")
                    + " to bean named '" + autowiredBeanName + "'");
        }
    }

    return args;
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

/**
 * Resolve the prepared arguments stored in the given bean definition.
 *//*www. ja  va 2s.  co m*/
private Object[] resolvePreparedArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
        Executable executable, Object[] argsToResolve, boolean fallback) {

    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd,
            converter);
    Class<?>[] paramTypes = executable.getParameterTypes();

    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forExecutable(executable, argIndex);
        GenericTypeResolver.resolveParameterType(methodParam, executable.getDeclaringClass());
        if (argValue instanceof AutowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter, fallback);
        } else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        } else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Class<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        } catch (TypeMismatchException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName,
                    new InjectionPoint(methodParam),
                    "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(argValue)
                            + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}