Search in sources :

Example 1 with BeanCreatedEventListener

use of io.micronaut.context.event.BeanCreatedEventListener 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 BeanCreatedEventListener

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

the class DefaultBeanContext method doCreateBean.

/**
 * Execution the creation of a bean. The returned value can be null if a
 * factory method returned null.
 *
 * @param resolutionContext The {@link BeanResolutionContext}
 * @param beanDefinition    The {@link BeanDefinition}
 * @param qualifier         The {@link Qualifier}
 * @param qualifierBeanType The bean type used in the qualifier
 * @param isSingleton       Whether the bean is a singleton
 * @param argumentValues    Any argument values passed to create the bean
 * @param <T>               The bean generic type
 * @return The created bean
 */
@Nullable
protected <T> T doCreateBean(@NonNull BeanResolutionContext resolutionContext, @NonNull BeanDefinition<T> beanDefinition, @Nullable Qualifier<T> qualifier, @Nullable Argument<T> qualifierBeanType, boolean isSingleton, @Nullable Map<String, Object> argumentValues) {
    if (argumentValues == null) {
        argumentValues = Collections.emptyMap();
    }
    Qualifier<T> declaredQualifier = beanDefinition.getDeclaredQualifier();
    Class<T> beanType = beanDefinition.getBeanType();
    if (isSingleton) {
        BeanRegistration<T> beanRegistration = singletonObjects.get(new BeanKey<>(beanDefinition, declaredQualifier));
        final Class<T> beanClass = qualifierBeanType.getType();
        if (beanRegistration != null) {
            if (qualifier == null || qualifier.reduce(beanClass, Stream.of(beanRegistration.beanDefinition)).findFirst().isPresent()) {
                return beanRegistration.bean;
            }
        } else if (qualifier != null) {
            beanRegistration = singletonObjects.get(new BeanKey<>(beanDefinition, null));
            if (beanRegistration != null && qualifier.reduce(beanClass, Stream.of(beanRegistration.beanDefinition)).findFirst().isPresent()) {
                return beanRegistration.bean;
            }
        }
    }
    T bean;
    if (beanDefinition instanceof BeanFactory) {
        BeanFactory<T> beanFactory = (BeanFactory<T>) beanDefinition;
        try {
            if (beanFactory instanceof ParametrizedBeanFactory) {
                ParametrizedBeanFactory<T> parametrizedBeanFactory = (ParametrizedBeanFactory<T>) beanFactory;
                Argument<?>[] requiredArguments = parametrizedBeanFactory.getRequiredArguments();
                Map<String, Object> convertedValues = new LinkedHashMap<>(argumentValues);
                for (Argument<?> requiredArgument : requiredArguments) {
                    String argumentName = requiredArgument.getName();
                    Object val = argumentValues.get(argumentName);
                    if (val == null && !requiredArgument.isDeclaredNullable()) {
                        throw new BeanInstantiationException(resolutionContext, "Missing bean argument [" + requiredArgument + "] for type: " + beanType.getName() + ". Required arguments: " + ArrayUtils.toString(requiredArguments));
                    }
                    Object convertedValue = null;
                    if (val != null) {
                        if (requiredArgument.getType().isInstance(val)) {
                            convertedValue = val;
                        } else {
                            convertedValue = ConversionService.SHARED.convert(val, requiredArgument).orElseThrow(() -> new BeanInstantiationException(resolutionContext, "Invalid bean argument [" + requiredArgument + "]. Cannot convert object [" + val + "] to required type: " + requiredArgument.getType()));
                        }
                    }
                    convertedValues.put(argumentName, convertedValue);
                }
                bean = parametrizedBeanFactory.build(resolutionContext, this, beanDefinition, convertedValues);
            } else {
                boolean propagateQualifier = beanDefinition.isProxy() && declaredQualifier instanceof Named;
                if (propagateQualifier) {
                    resolutionContext.setAttribute(BeanDefinition.NAMED_ATTRIBUTE, ((Named) declaredQualifier).getName());
                }
                resolutionContext.setCurrentQualifier(declaredQualifier != null ? declaredQualifier : qualifier);
                try {
                    bean = beanFactory.build(resolutionContext, this, beanDefinition);
                } finally {
                    resolutionContext.setCurrentQualifier(null);
                    if (propagateQualifier) {
                        resolutionContext.removeAttribute(BeanDefinition.NAMED_ATTRIBUTE);
                    }
                }
                if (bean == null) {
                    throw new BeanInstantiationException(resolutionContext, "Bean Factory [" + beanFactory + "] returned null");
                } else {
                    if (bean instanceof Qualified) {
                        ((Qualified) bean).$withBeanQualifier(declaredQualifier);
                    }
                }
            }
        } catch (Throwable e) {
            if (e instanceof DependencyInjectionException) {
                throw e;
            }
            if (e instanceof DisabledBeanException) {
                throw e;
            }
            if (e instanceof BeanInstantiationException) {
                throw e;
            } else {
                if (!resolutionContext.getPath().isEmpty()) {
                    throw new BeanInstantiationException(resolutionContext, e);
                } else {
                    throw new BeanInstantiationException(beanDefinition, e);
                }
            }
        }
    } else {
        ConstructorInjectionPoint<T> constructor = beanDefinition.getConstructor();
        Argument<?>[] requiredConstructorArguments = constructor.getArguments();
        if (requiredConstructorArguments.length == 0) {
            bean = constructor.invoke();
        } else {
            Object[] constructorArgs = new Object[requiredConstructorArguments.length];
            for (int i = 0; i < requiredConstructorArguments.length; i++) {
                Class<?> argument = requiredConstructorArguments[i].getType();
                constructorArgs[i] = getBean(resolutionContext, argument);
            }
            bean = constructor.invoke(constructorArgs);
        }
        inject(resolutionContext, null, bean);
    }
    if (bean != null) {
        Qualifier<T> finalQualifier = qualifier != null ? qualifier : declaredQualifier;
        if (!(bean instanceof BeanCreatedEventListener) && CollectionUtils.isNotEmpty(beanCreationEventListeners)) {
            for (Map.Entry<Class, List<BeanCreatedEventListener>> entry : beanCreationEventListeners) {
                if (entry.getKey().isAssignableFrom(beanType)) {
                    BeanKey<T> beanKey = new BeanKey<>(beanDefinition, finalQualifier);
                    for (BeanCreatedEventListener<?> listener : entry.getValue()) {
                        bean = (T) listener.onCreated(new BeanCreatedEvent(this, beanDefinition, beanKey, bean));
                        if (bean == null) {
                            throw new BeanInstantiationException(resolutionContext, "Listener [" + listener + "] returned null from onCreated event");
                        }
                    }
                }
            }
        }
        if (beanDefinition instanceof ValidatedBeanDefinition) {
            bean = ((ValidatedBeanDefinition<T>) beanDefinition).validate(resolutionContext, bean);
        }
        if (LOG_LIFECYCLE.isDebugEnabled()) {
            LOG_LIFECYCLE.debug("Created bean [{}] from definition [{}] with qualifier [{}]", bean, beanDefinition, finalQualifier);
        }
    }
    return bean;
}
Also used : Argument(io.micronaut.core.type.Argument) BeanCreatedEvent(io.micronaut.context.event.BeanCreatedEvent) LinkedHashMap(java.util.LinkedHashMap) ConcurrentLinkedHashMap(io.micronaut.core.util.clhm.ConcurrentLinkedHashMap) DependencyInjectionException(io.micronaut.context.exceptions.DependencyInjectionException) BeanFactory(io.micronaut.inject.BeanFactory) ParametrizedBeanFactory(io.micronaut.inject.ParametrizedBeanFactory) ParametrizedBeanFactory(io.micronaut.inject.ParametrizedBeanFactory) ArrayList(java.util.ArrayList) List(java.util.List) Named(io.micronaut.core.naming.Named) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) Qualified(io.micronaut.inject.qualifiers.Qualified) ValidatedBeanDefinition(io.micronaut.inject.ValidatedBeanDefinition) DisabledBeanException(io.micronaut.context.exceptions.DisabledBeanException) FieldInjectionPoint(io.micronaut.inject.FieldInjectionPoint) ConstructorInjectionPoint(io.micronaut.inject.ConstructorInjectionPoint) InjectionPoint(io.micronaut.inject.InjectionPoint) MethodInjectionPoint(io.micronaut.inject.MethodInjectionPoint) BeanCreatedEventListener(io.micronaut.context.event.BeanCreatedEventListener) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentLinkedHashMap(io.micronaut.core.util.clhm.ConcurrentLinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Nullable(io.micronaut.core.annotation.Nullable)

Aggregations

BeanCreatedEvent (io.micronaut.context.event.BeanCreatedEvent)2 BeanCreatedEventListener (io.micronaut.context.event.BeanCreatedEventListener)2 BeanInstantiationException (io.micronaut.context.exceptions.BeanInstantiationException)2 DependencyInjectionException (io.micronaut.context.exceptions.DependencyInjectionException)2 DisabledBeanException (io.micronaut.context.exceptions.DisabledBeanException)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 BeanDestroyedEvent (io.micronaut.context.event.BeanDestroyedEvent)1 BeanDestroyedEventListener (io.micronaut.context.event.BeanDestroyedEventListener)1