Search in sources :

Example 1 with BeanDefinitionMethodReference

use of io.micronaut.inject.BeanDefinitionMethodReference in project micronaut-core by micronaut-projects.

the class DefaultBeanContext method initializeContext.

/**
 * Initialize the context with the given {@link io.micronaut.context.annotation.Context} scope beans.
 *
 * @param contextScopeBeans The context scope beans
 * @param processedBeans    The beans that require {@link ExecutableMethodProcessor} handling
 * @param parallelBeans     The parallel bean definitions
 */
protected void initializeContext(@NonNull List<BeanDefinitionReference> contextScopeBeans, @NonNull List<BeanDefinitionReference> processedBeans, @NonNull List<BeanDefinitionReference> parallelBeans) {
    if (CollectionUtils.isNotEmpty(contextScopeBeans)) {
        final Collection<BeanDefinition> contextBeans = new ArrayList<>(contextScopeBeans.size());
        for (BeanDefinitionReference contextScopeBean : contextScopeBeans) {
            try {
                loadContextScopeBean(contextScopeBean, contextBeans::add);
            } catch (Throwable e) {
                throw new BeanInstantiationException("Bean definition [" + contextScopeBean.getName() + "] could not be loaded: " + e.getMessage(), e);
            }
        }
        filterProxiedTypes((Collection) contextBeans, true, false, null);
        filterReplacedBeans(null, (Collection) contextBeans);
        for (BeanDefinition contextScopeDefinition : contextBeans) {
            try {
                loadContextScopeBean(contextScopeDefinition);
            } catch (DisabledBeanException e) {
                if (AbstractBeanContextConditional.LOG.isDebugEnabled()) {
                    AbstractBeanContextConditional.LOG.debug("Bean of type [{}] disabled for reason: {}", contextScopeDefinition.getBeanType().getSimpleName(), e.getMessage());
                }
            } catch (Throwable e) {
                throw new BeanInstantiationException("Bean definition [" + contextScopeDefinition.getName() + "] could not be loaded: " + e.getMessage(), e);
            }
        }
    }
    if (!processedBeans.isEmpty()) {
        @SuppressWarnings("unchecked") Stream<BeanDefinitionMethodReference<?, ?>> methodStream = processedBeans.stream().filter(ref -> ref.isEnabled(this)).map((Function<BeanDefinitionReference, BeanDefinition<?>>) reference -> {
            try {
                return reference.load(this);
            } catch (Exception e) {
                throw new BeanInstantiationException("Bean definition [" + reference.getName() + "] could not be loaded: " + e.getMessage(), e);
            }
        }).filter(bean -> bean.isEnabled(this)).flatMap(beanDefinition -> beanDefinition.getExecutableMethods().parallelStream().filter(method -> method.hasStereotype(Executable.class)).map((Function<ExecutableMethod<?, ?>, BeanDefinitionMethodReference<?, ?>>) executableMethod -> BeanDefinitionMethodReference.of((BeanDefinition) beanDefinition, executableMethod)));
        // group the method references by annotation type such that we have a map of Annotation -> MethodReference
        // ie. Class<Scheduled> -> @Scheduled void someAnnotation()
        Map<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> byAnnotation = new HashMap<>(processedBeans.size());
        methodStream.forEach(reference -> {
            List<Class<? extends Annotation>> annotations = reference.getAnnotationTypesByStereotype(Executable.class);
            annotations.forEach(annotation -> byAnnotation.compute(annotation, (ann, list) -> {
                if (list == null) {
                    list = new ArrayList<>(10);
                }
                list.add(reference);
                return list;
            }));
        });
        // Find ExecutableMethodProcessor for each annotation and process the BeanDefinitionMethodReference
        byAnnotation.forEach((annotationType, methods) -> streamOfType(ExecutableMethodProcessor.class, Qualifiers.byTypeArguments(annotationType)).forEach(processor -> {
            if (processor instanceof LifeCycle<?>) {
                ((LifeCycle<?>) processor).start();
            }
            for (BeanDefinitionMethodReference<?, ?> method : methods) {
                BeanDefinition<?> beanDefinition = method.getBeanDefinition();
                // If declared at the class level it will already have been processed by AnnotationProcessorListener
                if (!beanDefinition.hasStereotype(annotationType)) {
                    // noinspection unchecked
                    if (method.hasDeclaredStereotype(Parallel.class)) {
                        ForkJoinPool.commonPool().execute(() -> {
                            try {
                                processor.process(beanDefinition, method);
                            } catch (Throwable e) {
                                if (LOG.isErrorEnabled()) {
                                    LOG.error("Error processing bean method " + beanDefinition + "." + method + " with processor (" + processor + "): " + e.getMessage(), e);
                                }
                                Boolean shutdownOnError = method.booleanValue(Parallel.class, "shutdownOnError").orElse(true);
                                if (shutdownOnError) {
                                    stop();
                                }
                            }
                        });
                    } else {
                        processor.process(beanDefinition, method);
                    }
                }
            }
            if (processor instanceof LifeCycle<?>) {
                ((LifeCycle<?>) processor).stop();
            }
        }));
    }
    if (CollectionUtils.isNotEmpty(parallelBeans)) {
        processParallelBeans(parallelBeans);
    }
    final Runnable runnable = () -> beanDefinitionsClasses.removeIf((BeanDefinitionReference beanDefinitionReference) -> !beanDefinitionReference.isEnabled(this));
    ForkJoinPool.commonPool().execute(runnable);
}
Also used : OrderUtil(io.micronaut.core.order.OrderUtil) Arrays(java.util.Arrays) BeanDestroyedEventListener(io.micronaut.context.event.BeanDestroyedEventListener) Internal(io.micronaut.core.annotation.Internal) DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) NonUniqueBeanException(io.micronaut.context.exceptions.NonUniqueBeanException) SoftServiceLoader(io.micronaut.core.io.service.SoftServiceLoader) Future(java.util.concurrent.Future) Map(java.util.Map) DefaultImplementation(io.micronaut.context.annotation.DefaultImplementation) Prototype(io.micronaut.context.annotation.Prototype) CustomScopeRegistry(io.micronaut.context.scope.CustomScopeRegistry) Ordered(io.micronaut.core.order.Ordered) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) TypeConverter(io.micronaut.core.convert.TypeConverter) Singleton(jakarta.inject.Singleton) Set(java.util.Set) ExecutableMethodProcessor(io.micronaut.context.processor.ExecutableMethodProcessor) BeanConfiguration(io.micronaut.inject.BeanConfiguration) FieldInjectionPoint(io.micronaut.inject.FieldInjectionPoint) EventListener(java.util.EventListener) Stream(java.util.stream.Stream) BeanPreDestroyEvent(io.micronaut.context.event.BeanPreDestroyEvent) BeanCreationException(io.micronaut.context.exceptions.BeanCreationException) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) ProxyBeanDefinition(io.micronaut.inject.ProxyBeanDefinition) ApplicationEventListener(io.micronaut.context.event.ApplicationEventListener) BeanFactory(io.micronaut.inject.BeanFactory) Replaces(io.micronaut.context.annotation.Replaces) AnnotationMetadataProvider(io.micronaut.core.annotation.AnnotationMetadataProvider) DisabledBeanException(io.micronaut.context.exceptions.DisabledBeanException) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Nullable(io.micronaut.core.annotation.Nullable) ReturnType(io.micronaut.core.type.ReturnType) Argument(io.micronaut.core.type.Argument) ConversionService(io.micronaut.core.convert.ConversionService) Qualified(io.micronaut.inject.qualifiers.Qualified) BeanDestructionException(io.micronaut.context.exceptions.BeanDestructionException) MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) BeanDefinitionMethodReference(io.micronaut.inject.BeanDefinitionMethodReference) ForkJoinPool(java.util.concurrent.ForkJoinPool) Named(io.micronaut.core.naming.Named) PropertyPlaceholderResolver(io.micronaut.context.env.PropertyPlaceholderResolver) BeanDefinition(io.micronaut.inject.BeanDefinition) Parallel(io.micronaut.context.annotation.Parallel) ValidatedBeanDefinition(io.micronaut.inject.ValidatedBeanDefinition) BeanContextException(io.micronaut.context.exceptions.BeanContextException) ListIterator(java.util.ListIterator) ArrayUtils(io.micronaut.core.util.ArrayUtils) LoggerFactory(org.slf4j.LoggerFactory) GenericTypeUtils(io.micronaut.core.reflect.GenericTypeUtils) StreamUtils(io.micronaut.core.util.StreamUtils) ConcurrentLinkedHashMap(io.micronaut.core.util.clhm.ConcurrentLinkedHashMap) PropertyResolver(io.micronaut.core.value.PropertyResolver) CreatedBean(io.micronaut.context.scope.CreatedBean) BeanCreatedEventListener(io.micronaut.context.event.BeanCreatedEventListener) Method(java.lang.reflect.Method) AnyQualifier(io.micronaut.inject.qualifiers.AnyQualifier) Executable(io.micronaut.context.annotation.Executable) ClassUtils(io.micronaut.core.reflect.ClassUtils) ConstructorInjectionPoint(io.micronaut.inject.ConstructorInjectionPoint) Context(io.micronaut.context.annotation.Context) BeanDestroyedEvent(io.micronaut.context.event.BeanDestroyedEvent) Predicate(java.util.function.Predicate) Collection(java.util.Collection) UsedByGeneratedCode(io.micronaut.core.annotation.UsedByGeneratedCode) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) BeanIdentifier(io.micronaut.inject.BeanIdentifier) Collectors(java.util.stream.Collectors) Indexes(io.micronaut.core.annotation.Indexes) ResourceLoader(io.micronaut.core.io.ResourceLoader) AnnotationProcessor(io.micronaut.context.processor.AnnotationProcessor) DisposableBeanDefinition(io.micronaut.inject.DisposableBeanDefinition) Objects(java.util.Objects) StringUtils(io.micronaut.core.util.StringUtils) List(java.util.List) AnnotationUtil(io.micronaut.core.annotation.AnnotationUtil) BeanCreatedEvent(io.micronaut.context.event.BeanCreatedEvent) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) BeanDefinitionReference(io.micronaut.inject.BeanDefinitionReference) InjectionPoint(io.micronaut.inject.InjectionPoint) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) BeanPreDestroyEventListener(io.micronaut.context.event.BeanPreDestroyEventListener) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) BeanInitializedEventListener(io.micronaut.context.event.BeanInitializedEventListener) Function(java.util.function.Function) ExecutableMethod(io.micronaut.inject.ExecutableMethod) BeanCreationContext(io.micronaut.context.scope.BeanCreationContext) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) HashSet(java.util.HashSet) Primary(io.micronaut.context.annotation.Primary) CustomScope(io.micronaut.context.scope.CustomScope) InitializingBeanDefinition(io.micronaut.inject.InitializingBeanDefinition) ConfigurationReader(io.micronaut.context.annotation.ConfigurationReader) Secondary(io.micronaut.context.annotation.Secondary) MutableConvertibleValues(io.micronaut.core.convert.value.MutableConvertibleValues) Infrastructure(io.micronaut.context.annotation.Infrastructure) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ApplicationEventPublisher(io.micronaut.context.event.ApplicationEventPublisher) AnnotationMetadataResolver(io.micronaut.core.annotation.AnnotationMetadataResolver) BeanDefinitionValidator(io.micronaut.inject.validation.BeanDefinitionValidator) AdvisedBeanType(io.micronaut.inject.AdvisedBeanType) ShutdownEvent(io.micronaut.context.event.ShutdownEvent) ValueResolver(io.micronaut.core.value.ValueResolver) BeanType(io.micronaut.inject.BeanType) Consumer(java.util.function.Consumer) NonNull(io.micronaut.core.annotation.NonNull) ClassPathResourceLoader(io.micronaut.core.io.scan.ClassPathResourceLoader) StartupEvent(io.micronaut.context.event.StartupEvent) MethodInjectionPoint(io.micronaut.inject.MethodInjectionPoint) ParametrizedBeanFactory(io.micronaut.inject.ParametrizedBeanFactory) Provider(jakarta.inject.Provider) CollectionUtils(io.micronaut.core.util.CollectionUtils) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) TypeConverterRegistrar(io.micronaut.core.convert.TypeConverterRegistrar) Comparator(java.util.Comparator) Collections(java.util.Collections) Order(io.micronaut.core.annotation.Order) BeanDefinitionMethodReference(io.micronaut.inject.BeanDefinitionMethodReference) LinkedHashMap(java.util.LinkedHashMap) ConcurrentLinkedHashMap(io.micronaut.core.util.clhm.ConcurrentLinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Parallel(io.micronaut.context.annotation.Parallel) 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) Function(java.util.function.Function) BeanDefinitionReference(io.micronaut.inject.BeanDefinitionReference) ArrayList(java.util.ArrayList) List(java.util.List) Executable(io.micronaut.context.annotation.Executable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) DisabledBeanException(io.micronaut.context.exceptions.DisabledBeanException) DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) NonUniqueBeanException(io.micronaut.context.exceptions.NonUniqueBeanException) BeanCreationException(io.micronaut.context.exceptions.BeanCreationException) DisabledBeanException(io.micronaut.context.exceptions.DisabledBeanException) BeanDestructionException(io.micronaut.context.exceptions.BeanDestructionException) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) BeanContextException(io.micronaut.context.exceptions.BeanContextException) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) Annotation(java.lang.annotation.Annotation)

Aggregations

ConfigurationReader (io.micronaut.context.annotation.ConfigurationReader)1 Context (io.micronaut.context.annotation.Context)1 DefaultImplementation (io.micronaut.context.annotation.DefaultImplementation)1 Executable (io.micronaut.context.annotation.Executable)1 Infrastructure (io.micronaut.context.annotation.Infrastructure)1 Parallel (io.micronaut.context.annotation.Parallel)1 Primary (io.micronaut.context.annotation.Primary)1 Prototype (io.micronaut.context.annotation.Prototype)1 Replaces (io.micronaut.context.annotation.Replaces)1 Secondary (io.micronaut.context.annotation.Secondary)1 PropertyPlaceholderResolver (io.micronaut.context.env.PropertyPlaceholderResolver)1 ApplicationEventListener (io.micronaut.context.event.ApplicationEventListener)1 ApplicationEventPublisher (io.micronaut.context.event.ApplicationEventPublisher)1 BeanCreatedEvent (io.micronaut.context.event.BeanCreatedEvent)1 BeanCreatedEventListener (io.micronaut.context.event.BeanCreatedEventListener)1 BeanDestroyedEvent (io.micronaut.context.event.BeanDestroyedEvent)1 BeanDestroyedEventListener (io.micronaut.context.event.BeanDestroyedEventListener)1 BeanInitializedEventListener (io.micronaut.context.event.BeanInitializedEventListener)1 BeanPreDestroyEvent (io.micronaut.context.event.BeanPreDestroyEvent)1 BeanPreDestroyEventListener (io.micronaut.context.event.BeanPreDestroyEventListener)1