Search in sources :

Example 1 with BeanInitializedEventListener

use of io.micronaut.context.event.BeanInitializedEventListener in project micronaut-core by micronaut-projects.

the class DefaultBeanContext method initializeEventListeners.

/**
 * Initialize the event listeners.
 */
protected void initializeEventListeners() {
    final Collection<BeanDefinition<BeanCreatedEventListener>> beanCreatedDefinitions = getBeanDefinitions(BeanCreatedEventListener.class);
    final HashMap<Class, List<BeanCreatedEventListener>> beanCreatedListeners = new HashMap<>(beanCreatedDefinitions.size());
    // noinspection ArraysAsListWithZeroOrOneArgument
    beanCreatedListeners.put(AnnotationProcessor.class, Arrays.asList(new AnnotationProcessorListener()));
    for (BeanDefinition<BeanCreatedEventListener> beanCreatedDefinition : beanCreatedDefinitions) {
        try (BeanResolutionContext context = newResolutionContext(beanCreatedDefinition, null)) {
            final BeanCreatedEventListener listener;
            final Qualifier qualifier = beanCreatedDefinition.getDeclaredQualifier();
            if (beanCreatedDefinition.isSingleton()) {
                listener = createAndRegisterSingleton(context, beanCreatedDefinition, beanCreatedDefinition.getBeanType(), qualifier);
            } else {
                listener = doCreateBean(context, beanCreatedDefinition, Argument.of(BeanCreatedEventListener.class), qualifier);
            }
            List<Argument<?>> typeArguments = beanCreatedDefinition.getTypeArguments(BeanCreatedEventListener.class);
            Argument<?> argument = CollectionUtils.last(typeArguments);
            if (argument == null) {
                argument = Argument.OBJECT_ARGUMENT;
            }
            beanCreatedListeners.computeIfAbsent(argument.getType(), aClass -> new ArrayList<>(10)).add(listener);
        }
    }
    for (List<BeanCreatedEventListener> listenerList : beanCreatedListeners.values()) {
        OrderUtil.sort(listenerList);
    }
    final HashMap<Class, List<BeanInitializedEventListener>> beanInitializedListeners = new HashMap<>(beanCreatedDefinitions.size());
    final Collection<BeanDefinition<BeanInitializedEventListener>> beanInitializedDefinitions = getBeanDefinitions(BeanInitializedEventListener.class);
    for (BeanDefinition<BeanInitializedEventListener> definition : beanInitializedDefinitions) {
        try (BeanResolutionContext context = newResolutionContext(definition, null)) {
            final Qualifier qualifier = definition.getDeclaredQualifier();
            final BeanInitializedEventListener listener;
            if (definition.isSingleton()) {
                listener = createAndRegisterSingleton(context, definition, definition.getBeanType(), qualifier);
            } else {
                listener = doCreateBean(context, definition, Argument.of(BeanInitializedEventListener.class), qualifier);
            }
            List<Argument<?>> typeArguments = definition.getTypeArguments(BeanInitializedEventListener.class);
            Argument<?> argument = CollectionUtils.last(typeArguments);
            if (argument == null) {
                argument = Argument.OBJECT_ARGUMENT;
            }
            beanInitializedListeners.computeIfAbsent(argument.getType(), aClass -> new ArrayList<>(10)).add(listener);
        }
    }
    for (List<BeanInitializedEventListener> listenerList : beanInitializedListeners.values()) {
        OrderUtil.sort(listenerList);
    }
    this.beanCreationEventListeners = beanCreatedListeners.entrySet();
    this.beanInitializedEventListeners = beanInitializedListeners.entrySet();
}
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) Argument(io.micronaut.core.type.Argument) LinkedHashMap(java.util.LinkedHashMap) ConcurrentLinkedHashMap(io.micronaut.core.util.clhm.ConcurrentLinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) 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) BeanCreatedEventListener(io.micronaut.context.event.BeanCreatedEventListener) ArrayList(java.util.ArrayList) List(java.util.List) AnyQualifier(io.micronaut.inject.qualifiers.AnyQualifier) BeanInitializedEventListener(io.micronaut.context.event.BeanInitializedEventListener)

Example 2 with BeanInitializedEventListener

use of io.micronaut.context.event.BeanInitializedEventListener in project micronaut-core by micronaut-projects.

the class AbstractBeanDefinition method postConstruct.

/**
 * Default postConstruct hook that only invokes methods that require reflection. Generated subclasses should
 * override to call methods that don't require reflection.
 *
 * @param resolutionContext The resolution hook
 * @param context           The context
 * @param bean              The bean
 * @return The bean
 */
@SuppressWarnings({ "unused", "unchecked" })
@Internal
@UsedByGeneratedCode
protected Object postConstruct(BeanResolutionContext resolutionContext, BeanContext context, Object bean) {
    boolean addInCreationHandling = isSingleton() && !CollectionUtils.isNotEmpty(postConstructMethods);
    DefaultBeanContext.BeanKey key = null;
    if (addInCreationHandling) {
        // ensure registration as an inflight bean if a post construct is present
        // this is to ensure that if the post construct method does anything funky to
        // cause recreation of this bean then we don't have a circular problem
        key = new DefaultBeanContext.BeanKey(this, resolutionContext.getCurrentQualifier());
        resolutionContext.addInFlightBean(key, bean);
    }
    final Set<Map.Entry<Class, List<BeanInitializedEventListener>>> beanInitializedEventListeners = ((DefaultBeanContext) context).beanInitializedEventListeners;
    if (CollectionUtils.isNotEmpty(beanInitializedEventListeners)) {
        for (Map.Entry<Class, List<BeanInitializedEventListener>> entry : beanInitializedEventListeners) {
            if (entry.getKey().isAssignableFrom(getBeanType())) {
                for (BeanInitializedEventListener listener : entry.getValue()) {
                    bean = listener.onInitialized(new BeanInitializingEvent(context, this, bean));
                    if (bean == null) {
                        throw new BeanInstantiationException(resolutionContext, "Listener [" + listener + "] returned null from onInitialized event");
                    }
                }
            }
        }
    }
    DefaultBeanContext defaultContext = (DefaultBeanContext) context;
    for (int i = 0; i < methodInjectionPoints.size(); i++) {
        MethodInjectionPoint methodInjectionPoint = methodInjectionPoints.get(i);
        if (methodInjectionPoint.isPostConstructMethod() && methodInjectionPoint.requiresReflection()) {
            injectBeanMethod(resolutionContext, defaultContext, i, bean);
        }
    }
    if (bean instanceof LifeCycle) {
        bean = ((LifeCycle) bean).start();
    }
    try {
        return bean;
    } finally {
        if (addInCreationHandling) {
            // ensure registration as an inflight bean if a post construct is present
            // this is to ensure that if the post construct method does anything funky to
            // cause recreation of this bean then we don't have a circular problem
            resolutionContext.removeInFlightBean(key);
        }
    }
}
Also used : BeanInitializingEvent(io.micronaut.context.event.BeanInitializingEvent) BeanInitializedEventListener(io.micronaut.context.event.BeanInitializedEventListener)

Aggregations

BeanInitializedEventListener (io.micronaut.context.event.BeanInitializedEventListener)2 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 BeanInitializingEvent (io.micronaut.context.event.BeanInitializingEvent)1 BeanPreDestroyEvent (io.micronaut.context.event.BeanPreDestroyEvent)1