Search in sources :

Example 6 with BeanContextException

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

the class AnnotationProcessorListener method onCreated.

@Override
public AnnotationProcessor onCreated(BeanCreatedEvent<AnnotationProcessor> event) {
    AnnotationProcessor processor = event.getBean();
    BeanDefinition<AnnotationProcessor> processorDefinition = event.getBeanDefinition();
    BeanContext beanContext = event.getSource();
    if (processor instanceof LifeCycle) {
        try {
            ((LifeCycle<?>) processor).start();
        } catch (Exception e) {
            throw new BeanContextException("Error starting bean processing: " + e.getMessage(), e);
        }
    }
    if (processor instanceof ExecutableMethodProcessor) {
        List<Argument<?>> typeArguments = processorDefinition.getTypeArguments(ExecutableMethodProcessor.class);
        if (!typeArguments.isEmpty()) {
            final Argument<?> firstArgument = typeArguments.get(0);
            Collection<BeanDefinition<?>> beanDefinitions = beanContext.getBeanDefinitions(Qualifiers.byStereotype((Class) firstArgument.getType()));
            boolean isParallel = firstArgument.isAnnotationPresent(Parallel.class);
            if (isParallel) {
                for (BeanDefinition<?> beanDefinition : beanDefinitions) {
                    Collection<? extends ExecutableMethod<?, ?>> executableMethods = beanDefinition.getExecutableMethods();
                    for (ExecutableMethod<?, ?> executableMethod : executableMethods) {
                        ForkJoinPool.commonPool().execute(() -> {
                            try {
                                if (beanContext.isRunning()) {
                                    processor.process(beanDefinition, executableMethod);
                                }
                            } catch (Throwable e) {
                                if (LOG.isErrorEnabled()) {
                                    LOG.error("Error processing bean method " + beanDefinition + "." + executableMethod + " with processor (" + processor + "): " + e.getMessage(), e);
                                }
                                Boolean shutdownOnError = executableMethod.getAnnotationMetadata().booleanValue(Parallel.class, "shutdownOnError").orElse(true);
                                if (shutdownOnError) {
                                    beanContext.stop();
                                }
                            }
                        });
                    }
                }
            } else {
                for (BeanDefinition<?> beanDefinition : beanDefinitions) {
                    Collection<? extends ExecutableMethod<?, ?>> executableMethods = beanDefinition.getExecutableMethods();
                    for (ExecutableMethod<?, ?> executableMethod : executableMethods) {
                        try {
                            processor.process(beanDefinition, executableMethod);
                        } catch (Exception e) {
                            throw new BeanContextException("Error processing bean [" + beanDefinition + "] method definition [" + executableMethod + "]: " + e.getMessage(), e);
                        }
                    }
                }
            }
        }
    } else if (processor instanceof BeanDefinitionProcessor) {
        BeanDefinitionProcessor beanDefinitionProcessor = (BeanDefinitionProcessor) processor;
        final List<Argument<?>> typeArguments = processorDefinition.getTypeArguments(BeanDefinitionProcessor.class);
        if (typeArguments.size() == 1) {
            final Argument<?> annotation = typeArguments.get(0);
            Collection<BeanDefinition<?>> beanDefinitions = beanContext.getBeanDefinitions(Qualifiers.byStereotype((Class) annotation.getType()));
            for (BeanDefinition<?> beanDefinition : beanDefinitions) {
                try {
                    beanDefinitionProcessor.process(beanDefinition, beanContext);
                } catch (Exception e) {
                    throw new BeanContextException("Error processing bean definition [" + beanDefinition + "]: " + e.getMessage(), e);
                }
            }
        }
    }
    if (processor instanceof LifeCycle) {
        try {
            ((LifeCycle<?>) processor).stop();
        } catch (Exception e) {
            throw new BeanContextException("Error finalizing bean processing: " + e.getMessage(), e);
        }
    }
    return processor;
}
Also used : Argument(io.micronaut.core.type.Argument) AnnotationProcessor(io.micronaut.context.processor.AnnotationProcessor) BeanDefinition(io.micronaut.inject.BeanDefinition) BeanDefinitionProcessor(io.micronaut.context.processor.BeanDefinitionProcessor) BeanContextException(io.micronaut.context.exceptions.BeanContextException) BeanContextException(io.micronaut.context.exceptions.BeanContextException) Collection(java.util.Collection) List(java.util.List) ExecutableMethodProcessor(io.micronaut.context.processor.ExecutableMethodProcessor)

Example 7 with BeanContextException

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

the class DefaultBeanContext method getBeanInternal.

private <T> T getBeanInternal(@Nullable BeanResolutionContext resolutionContext, @NonNull Argument<T> beanType, Qualifier<T> qualifier, boolean throwNonUnique, boolean throwNoSuchBean) {
    // allow injection the bean context
    final Class<T> beanClass = beanType.getType();
    if (thisInterfaces.contains(beanClass)) {
        return (T) this;
    }
    if (InjectionPoint.class.isAssignableFrom(beanClass)) {
        final BeanResolutionContext.Path path = resolutionContext != null ? resolutionContext.getPath() : null;
        if (CollectionUtils.isNotEmpty(path)) {
            final Iterator<BeanResolutionContext.Segment<?>> i = path.iterator();
            final BeanResolutionContext.Segment<?> injectionPointSegment = i.next();
            if (i.hasNext()) {
                BeanResolutionContext.Segment segment = i.next();
                final BeanDefinition declaringBean = segment.getDeclaringType();
                if (declaringBean.hasStereotype(INTRODUCTION_TYPE)) {
                    if (!i.hasNext()) {
                        if (!injectionPointSegment.getArgument().isNullable()) {
                            throw new BeanContextException("Failed to obtain injection point. No valid injection path present in path: " + path);
                        } else {
                            return null;
                        }
                    } else {
                        segment = i.next();
                    }
                }
                T ip = (T) segment.getInjectionPoint();
                if (beanClass.isInstance(ip)) {
                    return ip;
                } else {
                    if (!injectionPointSegment.getArgument().isNullable()) {
                        throw new DependencyInjectionException(resolutionContext, "Failed to obtain injection point. No valid injection path present in path: " + path);
                    } else {
                        return null;
                    }
                }
            } else {
                if (!injectionPointSegment.getArgument().isNullable()) {
                    throw new DependencyInjectionException(resolutionContext, "Failed to obtain injection point. No valid injection path present in path: " + path);
                } else {
                    return null;
                }
            }
        } else {
            throw new DependencyInjectionException(resolutionContext, "Failed to obtain injection point. No valid injection path present in path: " + path);
        }
    }
    BeanKey<T> beanKey = new BeanKey<>(beanType, qualifier);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Looking up existing bean for key: {}", beanKey);
    }
    T inFlightBean = resolutionContext != null ? resolutionContext.getInFlightBean(beanKey) : null;
    if (inFlightBean != null) {
        return inFlightBean;
    }
    BeanRegistration<T> beanRegistration = singletonObjects.get(beanKey);
    if (beanRegistration != null) {
        T bean = beanRegistration.bean;
        if (bean == null && throwNoSuchBean) {
            throw new NoSuchBeanException(beanType, qualifier);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resolved existing bean [{}] for type [{}] and qualifier [{}]", beanRegistration.bean, beanType, qualifier);
            }
            return bean;
        }
    } else if (LOG.isTraceEnabled()) {
        LOG.trace("No existing bean found for bean key: {}", beanKey);
    }
    synchronized (singletonObjects) {
        Optional<BeanDefinition<T>> concreteCandidate = findConcreteCandidate(resolutionContext, beanType, qualifier, throwNonUnique);
        T bean = null;
        if (concreteCandidate.isPresent()) {
            BeanDefinition<T> definition = concreteCandidate.get();
            if (definition.isContainerType() && beanClass != definition.getBeanType()) {
                throw new NonUniqueBeanException(beanClass, Collections.singletonList(definition).iterator());
            }
            if (definition.isSingleton()) {
                final BeanRegistration<T> registration = findExistingCompatibleSingleton(definition.asArgument(), beanType, qualifier, definition);
                if (registration != null) {
                    bean = registration.getBean();
                }
            }
            if (bean != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Resolved existing bean [{}] for type [{}] and qualifier [{}]", bean, beanType, qualifier);
                }
                return bean;
            } else {
                bean = getBeanForDefinition(resolutionContext, beanType, qualifier, throwNoSuchBean, definition);
                if (bean == null && throwNoSuchBean) {
                    throw new NoSuchBeanException(beanType, qualifier);
                } else {
                    return bean;
                }
            }
        } else {
            final BeanRegistration<T> registration = findExistingCompatibleSingleton(beanType, null, qualifier, null);
            if (registration != null) {
                bean = registration.getBean();
            }
            if (bean == null && throwNoSuchBean) {
                throw new NoSuchBeanException(beanType, qualifier);
            } else {
                return bean;
            }
        }
    }
}
Also used : NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) NonUniqueBeanException(io.micronaut.context.exceptions.NonUniqueBeanException) 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) DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) 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