Search in sources :

Example 1 with BeanContextException

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

the class DefaultBeanContext method findBeanCandidates.

/**
 * Find bean candidates for the given type.
 *
 * @param <T>               The bean generic type
 * @param resolutionContext The current resolution context
 * @param beanType          The bean type
 * @param filterProxied     Whether to filter out bean proxy targets
 * @param predicate         The predicate to filter candidates
 * @return The candidates
 */
@SuppressWarnings("unchecked")
@NonNull
protected <T> Collection<BeanDefinition<T>> findBeanCandidates(@Nullable BeanResolutionContext resolutionContext, @NonNull Argument<T> beanType, boolean filterProxied, Predicate<BeanDefinition<T>> predicate) {
    ArgumentUtils.requireNonNull("beanType", beanType);
    final Class<T> beanClass = beanType.getType();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Finding candidate beans for type: {}", beanType);
    }
    // first traverse component definition classes and load candidates
    Collection<BeanDefinitionReference> beanDefinitionsClasses;
    if (indexedTypes.contains(beanClass)) {
        beanDefinitionsClasses = beanIndex.get(beanClass);
        if (beanDefinitionsClasses == null) {
            beanDefinitionsClasses = Collections.emptyList();
        }
    } else {
        beanDefinitionsClasses = this.beanDefinitionsClasses;
    }
    if (!beanDefinitionsClasses.isEmpty()) {
        Set<BeanDefinition<T>> candidates = new HashSet<>();
        for (BeanDefinitionReference reference : beanDefinitionsClasses) {
            if (!reference.isCandidateBean(beanType) || !reference.isEnabled(this, resolutionContext)) {
                continue;
            }
            BeanDefinition<T> loadedBean;
            try {
                loadedBean = reference.load(this);
            } catch (Throwable e) {
                throw new BeanContextException("Error loading bean [" + reference.getName() + "]: " + e.getMessage(), e);
            }
            if (!loadedBean.isCandidateBean(beanType)) {
                continue;
            }
            if (predicate != null && !predicate.test(loadedBean)) {
                continue;
            }
            if (!loadedBean.isEnabled(this, resolutionContext)) {
                continue;
            }
            candidates.add(loadedBean);
        }
        if (!candidates.isEmpty()) {
            if (filterProxied) {
                filterProxiedTypes(candidates, true, false, null);
            }
            filterReplacedBeans(resolutionContext, candidates);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resolved bean candidates {} for type: {}", candidates, beanType);
        }
        return candidates;
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No bean candidates found for type: {}", beanType);
        }
        return Collections.emptySet();
    }
}
Also used : BeanContextException(io.micronaut.context.exceptions.BeanContextException) BeanDefinitionReference(io.micronaut.inject.BeanDefinitionReference) ProxyBeanDefinition(io.micronaut.inject.ProxyBeanDefinition) BeanDefinition(io.micronaut.inject.BeanDefinition) ValidatedBeanDefinition(io.micronaut.inject.ValidatedBeanDefinition) DisposableBeanDefinition(io.micronaut.inject.DisposableBeanDefinition) InitializingBeanDefinition(io.micronaut.inject.InitializingBeanDefinition) HashSet(java.util.HashSet) NonNull(io.micronaut.core.annotation.NonNull)

Example 2 with BeanContextException

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

the class AbstractInitializableBeanDefinition method setFieldWithReflection.

/**
 * Sets the value of a field of a object that requires reflection.
 *
 * @param resolutionContext The resolution context
 * @param context           The object context
 * @param index             The index of the field
 * @param object            The object whose field should be modifie
 * @param value             The instance being set
 */
@SuppressWarnings("unused")
@Internal
protected final void setFieldWithReflection(BeanResolutionContext resolutionContext, BeanContext context, int index, Object object, Object value) {
    FieldReference fieldRef = fieldInjection[index];
    try {
        if (ClassUtils.REFLECTION_LOGGER.isDebugEnabled()) {
            ClassUtils.REFLECTION_LOGGER.debug("Bean of type [" + getBeanType() + "] uses reflection to inject field: '" + fieldRef.argument.getName() + "'");
        }
        Field field = ReflectionUtils.getRequiredField(fieldRef.declaringType, fieldRef.argument.getName());
        field.setAccessible(true);
        field.set(object, value);
    } catch (Throwable e) {
        if (e instanceof BeanContextException) {
            throw (BeanContextException) e;
        } else {
            throw new DependencyInjectionException(resolutionContext, "Error setting field value: " + e.getMessage(), e);
        }
    }
}
Also used : Field(java.lang.reflect.Field) DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) BeanContextException(io.micronaut.context.exceptions.BeanContextException) Internal(io.micronaut.core.annotation.Internal)

Example 3 with BeanContextException

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

the class AbstractInitializableBeanDefinition method invokeMethodWithReflection.

/**
 * Invoke a bean method that requires reflection.
 *
 * @param resolutionContext The resolution context
 * @param context           The bean context
 * @param methodIndex       The method index
 * @param bean              The bean
 * @param methodArgs        The method args
 */
@Internal
@SuppressWarnings("WeakerAccess")
protected final void invokeMethodWithReflection(BeanResolutionContext resolutionContext, BeanContext context, int methodIndex, Object bean, Object[] methodArgs) {
    MethodReference methodRef = methodInjection[methodIndex];
    Argument[] methodArgumentTypes = methodRef.arguments == null ? Argument.ZERO_ARGUMENTS : methodRef.arguments;
    if (ClassUtils.REFLECTION_LOGGER.isDebugEnabled()) {
        ClassUtils.REFLECTION_LOGGER.debug("Bean of type [" + getBeanType() + "] uses reflection to inject method: '" + methodRef.methodName + "'");
    }
    try {
        Method method = ReflectionUtils.getMethod(methodRef.declaringType, methodRef.methodName, Argument.toClassArray(methodArgumentTypes)).orElseThrow(() -> ReflectionUtils.newNoSuchMethodError(methodRef.declaringType, methodRef.methodName, Argument.toClassArray(methodArgumentTypes)));
        method.setAccessible(true);
        ReflectionUtils.invokeMethod(bean, method, methodArgs);
    } catch (Throwable e) {
        if (e instanceof BeanContextException) {
            throw (BeanContextException) e;
        } else {
            throw new DependencyInjectionException(resolutionContext, "Error invoking method: " + methodRef.methodName, e);
        }
    }
}
Also used : DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) DefaultArgument(io.micronaut.core.type.DefaultArgument) Argument(io.micronaut.core.type.Argument) BeanContextException(io.micronaut.context.exceptions.BeanContextException) Method(java.lang.reflect.Method) ExecutableMethod(io.micronaut.inject.ExecutableMethod) Internal(io.micronaut.core.annotation.Internal)

Example 4 with BeanContextException

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

the class AbstractInitializableBeanDefinitionReference method isPresent.

@Override
public boolean isPresent() {
    if (present == null) {
        try {
            getBeanDefinitionType();
            getBeanType();
            present = true;
        } catch (Throwable e) {
            if (e instanceof TypeNotPresentException || e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Bean definition for type [" + beanTypeName + "] not loaded since it is not on the classpath", e);
                }
            } else {
                throw new BeanContextException("Unexpected error loading bean definition [" + beanDefinitionTypeName + "]: " + e.getMessage(), e);
            }
            present = false;
        }
    }
    return present;
}
Also used : BeanContextException(io.micronaut.context.exceptions.BeanContextException)

Example 5 with BeanContextException

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

the class AbstractBeanDefinitionReference method isPresent.

@Override
public boolean isPresent() {
    if (present == null) {
        try {
            getBeanDefinitionType();
            getBeanType();
            present = true;
        } catch (Throwable e) {
            if (e instanceof TypeNotPresentException || e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Bean definition for type [" + beanTypeName + "] not loaded since it is not on the classpath", e);
                }
            } else {
                throw new BeanContextException("Unexpected error loading bean definition [" + beanDefinitionTypeName + "]: " + e.getMessage(), e);
            }
            present = false;
        }
    }
    return present;
}
Also used : BeanContextException(io.micronaut.context.exceptions.BeanContextException)

Aggregations

BeanContextException (io.micronaut.context.exceptions.BeanContextException)7 DependencyInjectionException (io.micronaut.context.exceptions.DependencyInjectionException)3 BeanDefinition (io.micronaut.inject.BeanDefinition)3 Internal (io.micronaut.core.annotation.Internal)2 Argument (io.micronaut.core.type.Argument)2 DisposableBeanDefinition (io.micronaut.inject.DisposableBeanDefinition)2 InitializingBeanDefinition (io.micronaut.inject.InitializingBeanDefinition)2 ProxyBeanDefinition (io.micronaut.inject.ProxyBeanDefinition)2 ValidatedBeanDefinition (io.micronaut.inject.ValidatedBeanDefinition)2 NoSuchBeanException (io.micronaut.context.exceptions.NoSuchBeanException)1 NonUniqueBeanException (io.micronaut.context.exceptions.NonUniqueBeanException)1 AnnotationProcessor (io.micronaut.context.processor.AnnotationProcessor)1 BeanDefinitionProcessor (io.micronaut.context.processor.BeanDefinitionProcessor)1 ExecutableMethodProcessor (io.micronaut.context.processor.ExecutableMethodProcessor)1 NonNull (io.micronaut.core.annotation.NonNull)1 DefaultArgument (io.micronaut.core.type.DefaultArgument)1 BeanDefinitionReference (io.micronaut.inject.BeanDefinitionReference)1 ExecutableMethod (io.micronaut.inject.ExecutableMethod)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1