Search in sources :

Example 1 with NoSuchBeanException

use of io.micronaut.context.exceptions.NoSuchBeanException in project micronaut-core by micronaut-projects.

the class DefaultBeanContext method doCreateBean.

/**
 * @param resolutionContext The bean resolution context
 * @param definition        The bean definition
 * @param beanType          The bean type
 * @param qualifier         The qualifier
 * @param args              The argument values
 * @param <T>               the bean generic type
 * @return The instance
 */
@NonNull
protected <T> T doCreateBean(@NonNull BeanResolutionContext resolutionContext, @NonNull BeanDefinition<T> definition, @NonNull Argument<T> beanType, @Nullable Qualifier<T> qualifier, @Nullable Object... args) {
    Map<String, Object> argumentValues;
    if (definition instanceof ParametrizedBeanFactory) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Creating bean for parameters: {}", ArrayUtils.toString(args));
        }
        Argument[] requiredArguments = ((ParametrizedBeanFactory) definition).getRequiredArguments();
        argumentValues = new LinkedHashMap<>(requiredArguments.length);
        BeanResolutionContext.Path currentPath = resolutionContext.getPath();
        for (int i = 0; i < requiredArguments.length; i++) {
            Argument<?> requiredArgument = requiredArguments[i];
            try (BeanResolutionContext.Path ignored = currentPath.pushConstructorResolve(definition, requiredArgument)) {
                Class<?> argumentType = requiredArgument.getType();
                if (args.length > i) {
                    Object val = args[i];
                    if (val != null) {
                        if (argumentType.isInstance(val) && !CollectionUtils.isIterableOrMap(argumentType)) {
                            argumentValues.put(requiredArgument.getName(), val);
                        } else {
                            argumentValues.put(requiredArgument.getName(), ConversionService.SHARED.convert(val, requiredArgument).orElseThrow(() -> new BeanInstantiationException(resolutionContext, "Invalid bean @Argument [" + requiredArgument + "]. Cannot convert object [" + val + "] to required type: " + argumentType)));
                        }
                    } else {
                        if (!requiredArgument.isDeclaredNullable()) {
                            throw new BeanInstantiationException(resolutionContext, "Invalid bean @Argument [" + requiredArgument + "]. Argument cannot be null");
                        }
                    }
                } else {
                    // attempt resolve from context
                    Optional<?> existingBean = findBean(resolutionContext, argumentType, null);
                    if (existingBean.isPresent()) {
                        argumentValues.put(requiredArgument.getName(), existingBean.get());
                    } else {
                        if (!requiredArgument.isDeclaredNullable()) {
                            throw new BeanInstantiationException(resolutionContext, "Invalid bean @Argument [" + requiredArgument + "]. No bean found for type: " + argumentType);
                        }
                    }
                }
            }
        }
    } else {
        argumentValues = Collections.emptyMap();
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Computed bean argument values: {}", argumentValues);
    }
    T createdBean = doCreateBean(resolutionContext, definition, qualifier, beanType, false, argumentValues);
    if (createdBean == null) {
        throw new NoSuchBeanException(beanType);
    }
    return createdBean;
}
Also used : Argument(io.micronaut.core.type.Argument) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) FieldInjectionPoint(io.micronaut.inject.FieldInjectionPoint) ConstructorInjectionPoint(io.micronaut.inject.ConstructorInjectionPoint) InjectionPoint(io.micronaut.inject.InjectionPoint) MethodInjectionPoint(io.micronaut.inject.MethodInjectionPoint) ParametrizedBeanFactory(io.micronaut.inject.ParametrizedBeanFactory) NonNull(io.micronaut.core.annotation.NonNull)

Example 2 with NoSuchBeanException

use of io.micronaut.context.exceptions.NoSuchBeanException in project micronaut-core by micronaut-projects.

the class AbstractInitializableBeanDefinition method getPropertyPlaceholderValueForConstructorArgument.

/**
 * Obtains a property value for a bean definition for a constructor at the given index
 * <p>
 * Warning: this method is used by internal generated code and should not be called by user code.
 *
 * @param resolutionContext The resolution context
 * @param context           The context
 * @param argIndex          The argument index
 * @param propertyValue     The property value
 * @return The resolved bean
 */
@Internal
@UsedByGeneratedCode
protected final Object getPropertyPlaceholderValueForConstructorArgument(BeanResolutionContext resolutionContext, BeanContext context, int argIndex, String propertyValue) {
    MethodReference constructorRef = (MethodReference) constructor;
    Argument<?> argument = constructorRef.arguments[argIndex];
    try (BeanResolutionContext.Path ignored = resolutionContext.getPath().pushConstructorResolve(this, argument)) {
        try {
            Object result = resolvePropertyValue(resolutionContext, context, argument, propertyValue, null, true);
            if (this instanceof ValidatedBeanDefinition) {
                ((ValidatedBeanDefinition) this).validateBeanArgument(resolutionContext, getConstructor(), argument, argIndex, result);
            }
            return result;
        } catch (NoSuchBeanException | BeanInstantiationException e) {
            throw new DependencyInjectionException(resolutionContext, argument, e);
        }
    }
}
Also used : DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) ValidatedBeanDefinition(io.micronaut.inject.ValidatedBeanDefinition) Internal(io.micronaut.core.annotation.Internal) UsedByGeneratedCode(io.micronaut.core.annotation.UsedByGeneratedCode)

Example 3 with NoSuchBeanException

use of io.micronaut.context.exceptions.NoSuchBeanException in project micronaut-core by micronaut-projects.

the class AbstractInitializableBeanDefinition method resolveBeanRegistrations.

private <B> Collection<BeanRegistration<B>> resolveBeanRegistrations(BeanResolutionContext resolutionContext, BeanContext beanContext, Argument argument, Argument genericArgument, Qualifier qualifier) {
    try {
        if (genericArgument == null) {
            throw new DependencyInjectionException(resolutionContext, "Cannot resolve bean registrations. Argument [" + argument + "] missing generic type information.");
        }
        qualifier = qualifier == null ? resolveQualifier(resolutionContext, argument) : qualifier;
        Collection beanRegistrations = ((DefaultBeanContext) beanContext).getBeanRegistrations(resolutionContext, genericArgument, qualifier);
        return coerceCollectionToCorrectType(argument.getType(), beanRegistrations, resolutionContext, argument);
    } catch (NoSuchBeanException e) {
        if (argument.isNullable()) {
            return null;
        }
        throw new DependencyInjectionException(resolutionContext, e);
    }
}
Also used : DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) Collection(java.util.Collection)

Example 4 with NoSuchBeanException

use of io.micronaut.context.exceptions.NoSuchBeanException in project micronaut-core by micronaut-projects.

the class AbstractProviderDefinition method build.

@Override
public T build(BeanResolutionContext resolutionContext, BeanContext context, BeanDefinition<T> definition) throws BeanInstantiationException {
    final BeanResolutionContext.Segment<?> segment = resolutionContext.getPath().currentSegment().orElse(null);
    if (segment != null) {
        final InjectionPoint<?> injectionPoint = segment.getInjectionPoint();
        if (injectionPoint instanceof ArgumentCoercible) {
            Argument<?> injectionPointArgument = ((ArgumentCoercible<?>) injectionPoint).asArgument();
            Argument<?> resolveArgument = injectionPointArgument;
            if (resolveArgument.isOptional()) {
                resolveArgument = resolveArgument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
            }
            @SuppressWarnings("unchecked") Argument<Object> argument = (Argument<Object>) resolveArgument.getFirstTypeVariable().orElse(null);
            if (argument != null) {
                Qualifier<Object> qualifier = (Qualifier<Object>) resolutionContext.getCurrentQualifier();
                if (qualifier == null && segment.getDeclaringType().isIterable()) {
                    final Object n = resolutionContext.getAttribute(Named.class.getName());
                    if (n != null) {
                        qualifier = Qualifiers.byName(n.toString());
                    }
                }
                boolean hasBean = context.containsBean(argument, qualifier);
                if (hasBean) {
                    return buildProvider(resolutionContext, context, argument, qualifier, definition.isSingleton());
                } else {
                    if (injectionPointArgument.isOptional()) {
                        return (T) Optional.empty();
                    } else if (injectionPointArgument.isNullable()) {
                        throw new DisabledBeanException("Nullable bean doesn't exist");
                    } else {
                        if (qualifier instanceof AnyQualifier || isAllowEmptyProviders(context)) {
                            return buildProvider(resolutionContext, context, argument, qualifier, definition.isSingleton());
                        } else {
                            throw new NoSuchBeanException(argument, qualifier);
                        }
                    }
                }
            }
        }
    }
    throw new UnsupportedOperationException("Cannot inject provider for Object type");
}
Also used : Named(io.micronaut.core.naming.Named) Argument(io.micronaut.core.type.Argument) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) ArgumentCoercible(io.micronaut.core.type.ArgumentCoercible) DisabledBeanException(io.micronaut.context.exceptions.DisabledBeanException) AnyQualifier(io.micronaut.inject.qualifiers.AnyQualifier) Qualifier(io.micronaut.context.Qualifier) AnyQualifier(io.micronaut.inject.qualifiers.AnyQualifier) BeanResolutionContext(io.micronaut.context.BeanResolutionContext)

Example 5 with NoSuchBeanException

use of io.micronaut.context.exceptions.NoSuchBeanException in project micronaut-core by micronaut-projects.

the class AbstractInitializableBeanDefinition method getValueForConstructorArgument.

/**
 * Obtains a value for a bean definition for a constructor at the given index
 * <p>
 * Warning: this method is used by internal generated code and should not be called by user code.
 *
 * @param resolutionContext The resolution context
 * @param context           The context
 * @param argIndex          The argument index
 * @param qualifier         The qualifier
 * @return The resolved bean
 */
@Internal
@UsedByGeneratedCode
@Deprecated
protected final Object getValueForConstructorArgument(BeanResolutionContext resolutionContext, BeanContext context, int argIndex, Qualifier qualifier) {
    MethodReference constructorRef = (MethodReference) constructor;
    Argument<?> argument = constructorRef.arguments[argIndex];
    try (BeanResolutionContext.Path ignored = resolutionContext.getPath().pushConstructorResolve(this, argument)) {
        try {
            Object result = resolveValue(resolutionContext, context, constructorRef.annotationMetadata, argument, qualifier);
            if (this instanceof ValidatedBeanDefinition) {
                ((ValidatedBeanDefinition) this).validateBeanArgument(resolutionContext, getConstructor(), argument, argIndex, result);
            }
            return result;
        } catch (NoSuchBeanException | BeanInstantiationException e) {
            throw new DependencyInjectionException(resolutionContext, argument, e);
        }
    }
}
Also used : DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) ValidatedBeanDefinition(io.micronaut.inject.ValidatedBeanDefinition) Internal(io.micronaut.core.annotation.Internal) UsedByGeneratedCode(io.micronaut.core.annotation.UsedByGeneratedCode)

Aggregations

NoSuchBeanException (io.micronaut.context.exceptions.NoSuchBeanException)8 DependencyInjectionException (io.micronaut.context.exceptions.DependencyInjectionException)5 ValidatedBeanDefinition (io.micronaut.inject.ValidatedBeanDefinition)5 BeanInstantiationException (io.micronaut.context.exceptions.BeanInstantiationException)4 Internal (io.micronaut.core.annotation.Internal)3 UsedByGeneratedCode (io.micronaut.core.annotation.UsedByGeneratedCode)3 Argument (io.micronaut.core.type.Argument)2 BeanDefinition (io.micronaut.inject.BeanDefinition)2 ConstructorInjectionPoint (io.micronaut.inject.ConstructorInjectionPoint)2 DisposableBeanDefinition (io.micronaut.inject.DisposableBeanDefinition)2 FieldInjectionPoint (io.micronaut.inject.FieldInjectionPoint)2 InitializingBeanDefinition (io.micronaut.inject.InitializingBeanDefinition)2 InjectionPoint (io.micronaut.inject.InjectionPoint)2 MethodInjectionPoint (io.micronaut.inject.MethodInjectionPoint)2 ProxyBeanDefinition (io.micronaut.inject.ProxyBeanDefinition)2 BeanResolutionContext (io.micronaut.context.BeanResolutionContext)1 Qualifier (io.micronaut.context.Qualifier)1 BeanContextException (io.micronaut.context.exceptions.BeanContextException)1 DisabledBeanException (io.micronaut.context.exceptions.DisabledBeanException)1 NonUniqueBeanException (io.micronaut.context.exceptions.NonUniqueBeanException)1