io.micronaut.inject.BeanDefinition Java Examples

The following examples show how to use io.micronaut.inject.BeanDefinition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Override
public @Nonnull
String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
    // ignore certain common cases
    if (type == null || Object.class == type || List.class == type || beanExcludes.contains(type)) {
        return StringUtils.EMPTY_STRING_ARRAY;
    }
    String[] names = beanNamesForTypeCache.get(type);
    if (names == null) {
        final String[] superResult = MicronautBeanFactory.super.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
        if (ArrayUtils.isNotEmpty(superResult)) {
            names = superResult;
        } else {
            final Collection<? extends BeanDefinition<?>> beanDefinitions = beanContext.getBeanDefinitions(type);
            names = beansToNames(beanDefinitions);
        }
        beanNamesForTypeCache.put(type, names);
    }
    return names;
}
 
Example #2
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
private String computeBeanName(BeanDefinition<?> definition) {
    String name;
    if (definition instanceof NameResolver) {
        name = ((NameResolver) definition).resolveName().orElse(Primary.class.getSimpleName());
    } else {
        name = definition.getValue(Named.class, String.class).orElseGet(() ->
                definition.getAnnotationTypeByStereotype(Qualifier.class).map(Class::getSimpleName).orElse(definition.getClass().getSimpleName())
        );
    }
    return definition.getBeanType().getName() + "(" + name + ")";
}
 
Example #3
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isPrimary(String beanName, Object beanInstance) {
    BeanDefinitionReference<?> reference = beanDefinitionMap.get(beanName);
    if (reference == null) {
        reference = beanDefinitionsByName.get(beanName);
    }

    if (reference != null) {
        final BeanDefinition<?> definition = reference.load(beanContext);
        return definition.hasDeclaredStereotype(Primary.class) || definition.getValue(Named.class, String.class).map((String n) -> Primary.class.getName().equals(n)).orElse(false);
    } else {
        return false;
    }
}
 
Example #4
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public void registerBeanDefinition(String beanName, org.springframework.beans.factory.config.BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
    if (beanDefinition instanceof org.springframework.beans.factory.support.AbstractBeanDefinition) {
        org.springframework.beans.factory.support.AbstractBeanDefinition abstractBeanDefinition = (org.springframework.beans.factory.support.AbstractBeanDefinition) beanDefinition;
        final Supplier<?> instanceSupplier = abstractBeanDefinition.getInstanceSupplier();
        if (instanceSupplier != null) {
            registerSingleton(beanName, instanceSupplier.get());
        }
    }
}
 
Example #5
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyBean(String beanName, Object beanInstance) {
    final BeanDefinitionReference<?> reference = beanDefinitionMap.get(beanName);
    if (reference != null) {
        final BeanDefinition<?> ref = reference.load(beanContext);
        if (ref instanceof DisposableBeanDefinition) {
            ((DisposableBeanDefinition) ref).dispose(beanContext, beanInstance);
        }
    }
}
 
Example #6
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public org.springframework.beans.factory.config.BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
    final BeanDefinitionReference<?> reference = beanDefinitionMap.get(beanName);
    if (reference != null) {
        final BeanDefinition<?> def = reference.load(beanContext);
        if (def.isEnabled(beanContext)) {
            final GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
            genericBeanDefinition.setBeanClass(def.getBeanType());
            return genericBeanDefinition;
        }
    }
    throw new NoSuchBeanDefinitionException(beanName);
}
 
Example #7
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
@Override
public @Nonnull
String[] getBeanNamesForAnnotation(@Nonnull Class<? extends Annotation> annotationType) {
    final String[] beanNamesForAnnotation = super.getBeanNamesForAnnotation(annotationType);
    final Collection<BeanDefinition<?>> beanDefinitions = beanContext.getBeanDefinitions(Qualifiers.byStereotype(annotationType));
    return ArrayUtils.concat(beansToNames(beanDefinitions), beanNamesForAnnotation);
}
 
Example #8
Source File: GoogleMethodRouteBuilder.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
@Override
protected UriRoute buildBeanRoute(String httpMethodName, HttpMethod httpMethod, String uri, BeanDefinition<?> beanDefinition, ExecutableMethod<?, ?> method) {
    String cp = contextPathProvider.getContextPath();
    if (cp != null) {
        uri = StringUtils.prependUri(cp, uri);
    }
    return super.buildBeanRoute(httpMethodName, httpMethod, uri, beanDefinition, method);
}
 
Example #9
Source File: GrpcChannelScope.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(
        BeanResolutionContext resolutionContext,
        BeanDefinition<T> beanDefinition,
        BeanIdentifier identifier,
        Provider<T> provider) {
    BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
            new IllegalStateException("@GrpcChannel used in invalid location")
    );
    Argument argument = segment.getArgument();
    String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null);
    if (StringUtils.isEmpty(value)) {
        throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation");
    }
    if (!Channel.class.isAssignableFrom(argument.getType())) {
        throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel");
    }

    if ("grpc-server".equalsIgnoreCase(value)) {
        return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server"));
    }

    if (!(provider instanceof ParametrizedProvider)) {
        throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider");
    }
    value = applicationContext.resolveRequiredPlaceholders(value);
    String finalValue = value;
    return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey ->
            (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue)
    );
}
 
Example #10
Source File: Registry.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
public Registry(ApplicationContext applicationContext) {
    Collection<BeanDefinition<CommandHandler>> commandHandlers = applicationContext.getBeanDefinitions(CommandHandler.class);
    commandHandlers.forEach(x -> registerCommand(applicationContext, x));

    Collection<BeanDefinition<QueryHandler>> queryHandlers = applicationContext.getBeanDefinitions(QueryHandler.class);
    queryHandlers.forEach(x -> registerQuery(applicationContext, x));
}
 
Example #11
Source File: DefaultJdbcRepositoryOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 *
 * @param dataSourceName        The data source name
 * @param dataSource            The datasource
 * @param transactionOperations The JDBC operations for the data source
 * @param executorService       The executor service
 * @param beanContext           The bean context
 * @param codecs                The codecs
 * @param dateTimeProvider      The dateTimeProvider
 */
protected DefaultJdbcRepositoryOperations(@Parameter String dataSourceName,
                                          DataSource dataSource,
                                          @Parameter TransactionOperations<Connection> transactionOperations,
                                          @Named("io") @Nullable ExecutorService executorService,
                                          BeanContext beanContext,
                                          List<MediaTypeCodec> codecs,
                                          @NonNull DateTimeProvider dateTimeProvider) {
    super(
            new ColumnNameResultSetReader(),
            new ColumnIndexResultSetReader(),
            new JdbcQueryStatement(),
            codecs,
            dateTimeProvider
    );
    ArgumentUtils.requireNonNull("dataSource", dataSource);
    ArgumentUtils.requireNonNull("transactionOperations", transactionOperations);
    this.dataSource = dataSource;
    this.transactionOperations = transactionOperations;
    this.executorService = executorService;
    Collection<BeanDefinition<GenericRepository>> beanDefinitions = beanContext.getBeanDefinitions(GenericRepository.class, Qualifiers.byStereotype(Repository.class));
    for (BeanDefinition<GenericRepository> beanDefinition : beanDefinitions) {
        String targetDs = beanDefinition.stringValue(Repository.class).orElse("default");
        if (targetDs.equalsIgnoreCase(dataSourceName)) {
            Dialect dialect = beanDefinition.enumValue(JdbcRepository.class, "dialect", Dialect.class).orElseGet(() -> beanDefinition.enumValue(JdbcRepository.class, "dialectName", Dialect.class).orElse(Dialect.ANSI));
            dialects.put(beanDefinition.getBeanType(), dialect);
            QueryBuilder qb = queryBuilders.get(dialect);
            if (qb == null) {
                queryBuilders.put(dialect, new SqlQueryBuilder(dialect));
            }
        }
    }
}
 
Example #12
Source File: KafkaClientScope.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(BeanResolutionContext resolutionContext, BeanDefinition<T> beanDefinition, BeanIdentifier identifier, Provider<T> provider) {
    BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
            new IllegalStateException("@KafkaClient used in invalid location")
    );
    Argument argument = segment.getArgument();
    AnnotationValue<KafkaClient> annotation = argument.findAnnotation(KafkaClient.class)
                                                      .orElseThrow(() -> new DependencyInjectionException(resolutionContext, argument, "KafkaClientScope called for injection point that is not annotated with @KafkaClient"));
    if (!Producer.class.isAssignableFrom(argument.getType())) {
        throw new DependencyInjectionException(resolutionContext, argument, "@KafkaClient used on type that is not a " + Producer.class.getName());
    }
    if (!(provider instanceof ParametrizedProvider)) {
        throw new DependencyInjectionException(resolutionContext, argument, "KafkaClientScope called with invalid bean provider");
    }

    Optional<Argument<?>> k = argument.getTypeVariable("K");
    Optional<Argument<?>> v = argument.getTypeVariable("V");

    if (!k.isPresent() || !v.isPresent()) {
        throw new DependencyInjectionException(resolutionContext, argument, "@KafkaClient used on type missing generic argument values for Key and Value");

    }

    String id = annotation.getValue(String.class).orElse(null);
    Argument<?> keyArgument = k.get();
    Argument<?> valueArgument = v.get();
    return getKafkaProducer(id, keyArgument, valueArgument);
}
 
Example #13
Source File: GrpcChannelScope.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(
        BeanResolutionContext resolutionContext,
        BeanDefinition<T> beanDefinition,
        BeanIdentifier identifier,
        Provider<T> provider) {
    BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
            new IllegalStateException("@GrpcChannel used in invalid location")
    );
    Argument argument = segment.getArgument();
    String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null);
    if (StringUtils.isEmpty(value)) {
        throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation");
    }
    if (!Channel.class.isAssignableFrom(argument.getType())) {
        throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel");
    }

    if ("grpc-server".equalsIgnoreCase(value)) {
        return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server"));
    }

    if (!(provider instanceof ParametrizedProvider)) {
        throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider");
    }
    value = applicationContext.resolveRequiredPlaceholders(value);
    String finalValue = value;
    return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey ->
            (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue)
    );
}
 
Example #14
Source File: Registry.java    From micronaut-microservices-poc with Apache License 2.0 4 votes vote down vote up
private void registerQuery(ApplicationContext applicationContext, BeanDefinition<QueryHandler> bean) {
    Class<QueryHandler> handlerClass = bean.getBeanType();
    Class<?>[] generics = GenericTypeUtils.resolveInterfaceTypeArguments(handlerClass, QueryHandler.class);
    Class<? extends Query> queryType = (Class<? extends Query>) generics[1];
    queryProviderMap.put(queryType, new QueryProvider(applicationContext, handlerClass));
}
 
Example #15
Source File: Registry.java    From micronaut-microservices-poc with Apache License 2.0 4 votes vote down vote up
private void registerCommand(ApplicationContext applicationContext, BeanDefinition<CommandHandler> bean) {
    Class<CommandHandler> handlerClass = bean.getBeanType();
    Class<?>[] generics = GenericTypeUtils.resolveInterfaceTypeArguments(handlerClass, CommandHandler.class);
    Class<? extends Command> commandType = (Class<? extends Command>) generics[1];
    commandProviderMap.put(commandType, new CommandProvider(applicationContext, handlerClass));
}
 
Example #16
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getType(@Nonnull String beanName) throws NoSuchBeanDefinitionException {
    Optional<Class<?>> opt = beanTypeCache.get(beanName);
    //noinspection OptionalAssignedToNull
    if (opt == null) {
        final BeanDefinitionReference<?> definition = beanDefinitionMap.get(beanName);
        if (definition != null) {
            opt = Optional.of(definition.getBeanType());
        } else {

            beanName = transformedBeanName(beanName);
            // Check manually registered singletons.
            Object beanInstance = super.getSingleton(beanName, false);
            if (beanInstance != null && !beanInstance.getClass().getSimpleName().equals("NullBean")) {
                if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(beanName)) {
                    return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
                } else {
                    return beanInstance.getClass();
                }
            }
            // No singleton instance found -> check bean definition.
            org.springframework.beans.factory.BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // No bean definition found in this factory -> delegate to parent.
                return parentBeanFactory.getType(originalBeanName(beanName));
            }

            final org.springframework.beans.factory.config.BeanDefinition parentDef;
            try {
                parentDef = super.getBeanDefinition(beanName);
            } catch (NoSuchBeanDefinitionException e) {
                beanTypeCache.put(beanName, Optional.empty());
                return null;
            }
            if (parentDef instanceof RootBeanDefinition) {

                RootBeanDefinition mbd = (RootBeanDefinition) parentDef;

                // Check decorated bean definition, if any: We assume it'll be easier
                // to determine the decorated bean's type than the proxy's type.
                BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
                if (dbd != null && !BeanFactoryUtils.isFactoryDereference(beanName)) {
                    RootBeanDefinition tbd = super.getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
                    Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
                    if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
                        return targetClass;
                    }
                }

                Class<?> beanClass = predictBeanType(beanName, mbd);

                // Check bean class whether we're dealing with a FactoryBean.
                if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
                    if (!BeanFactoryUtils.isFactoryDereference(beanName)) {
                        // If it's a FactoryBean, we want to look at what it creates, not at the factory class.
                        return super.getTypeForFactoryBean(beanName, mbd);
                    } else {
                        return beanClass;
                    }
                } else {
                    return (!BeanFactoryUtils.isFactoryDereference(beanName) ? beanClass : null);
                }
            }
        }
        beanTypeCache.put(beanName, opt);
    }

    return opt.orElse(null);
}
 
Example #17
Source File: TestActiveCondition.java    From micronaut-test with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(ConditionContext context) {
    if (context.getComponent() instanceof BeanDefinition) {
        BeanDefinition<?> definition = (BeanDefinition<?>) context.getComponent();
        final BeanContext beanContext = context.getBeanContext();
        final Optional<Class<?>> declaringType = definition.getDeclaringType();

        if (beanContext instanceof ApplicationContext) {
            ApplicationContext applicationContext = (ApplicationContext) beanContext;
            final Class activeSpecClazz = applicationContext.get(ACTIVE_SPEC_CLAZZ, Class.class).orElse(null);
            final String activeSpecName = Optional.ofNullable(activeSpecClazz).map(clazz -> clazz.getPackage().getName() + "." + clazz.getSimpleName()).orElse(null);
            if (definition.isAnnotationPresent(MockBean.class) && declaringType.isPresent()) {
                final Class<?> declaringTypeClass = declaringType.get();
                String declaringTypeName = declaringTypeClass.getName();
                if (activeSpecClazz != null) {
                    if (definition.isProxy()) {
                        final String packageName = NameUtils.getPackageName(activeSpecName);
                        final String simpleName = NameUtils.getSimpleName(activeSpecName);
                        final String rootName = packageName + ".$" + simpleName;
                        return declaringTypeClass.isAssignableFrom(activeSpecClazz) || declaringTypeName.equals(rootName) || declaringTypeName.startsWith(rootName + "$");
                    } else {
                        return declaringTypeClass.isAssignableFrom(activeSpecClazz) || activeSpecName.equals(declaringTypeName) || declaringTypeName.startsWith(activeSpecName + "$");
                    }
                } else {
                    context.fail(
                            "@MockBean of type " + definition.getBeanType() + " not within scope of parent test."
                    );
                    return false;
                }
            } else {
                if (activeSpecName != null) {
                    boolean beanTypeMatches = activeSpecName.equals(definition.getBeanType().getName());
                    return beanTypeMatches || (declaringType.isPresent() && activeSpecClazz == declaringType.get());
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    } else {
        return true;
    }
}
 
Example #18
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
private String[] beansToNames(Collection<? extends BeanDefinition<?>> beanDefinitions) {
    return beanDefinitions.stream()
            .filter(bd -> !(bd instanceof ParametrizedBeanFactory))
            .map(this::computeBeanName).toArray(String[]::new);
}
 
Example #19
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected <T> T doGetBean(String name, Class<T> requiredType, Object[] args, boolean typeCheckOnly) throws BeansException {

    if (beanExcludes.contains(requiredType)) {
        throw new NoSuchBeanDefinitionException(name);
    }

    if (super.containsSingleton(name)) {
        final Object o = super.getSingleton(name);
        if (requiredType == null || requiredType.isInstance(o)) {
            return (T) o;
        }
    }

    BeanDefinitionReference<?> reference = beanDefinitionMap.get(name);
    if (reference == null) {
        // by name, with no type lookups
        final BeanDefinitionReference<?> ref = beanDefinitionsByName.get(name);
        if (ref != null) {
            if (requiredType != null) {
                if (requiredType.isAssignableFrom(ref.getBeanType())) {
                    reference = ref;
                }
            } else {
                reference = ref;
            }
        }
    }

    if (reference != null) {
        final BeanDefinition<?> definition = reference.load(beanContext);
        if (definition.isEnabled(beanContext)) {
            if (requiredType == null) {
                requiredType = (Class<T>) definition.getBeanType();
            }

            io.micronaut.context.Qualifier<T> q = (io.micronaut.context.Qualifier<T>) definition.getValue(Named.class, String.class)
                    .map((String n) -> {
                        if (Primary.class.getName().equals(n)) {
                            return n;
                        }
                        return Qualifiers.byName(n);
                    })
                    .orElseGet(() -> {
                                if (definition.hasDeclaredStereotype(Primary.class)) {
                                    return null;
                                }
                                final Class annotationType = definition.getAnnotationTypeByStereotype(Qualifier.class).orElse(null);
                                if (annotationType != null) {
                                    return Qualifiers.byAnnotation(definition, annotationType);
                                }
                                return null;
                            }
                    );
            if (q != null) {
                return beanContext.getBean(requiredType, q);
            } else {
                return beanContext.getBean(requiredType);
            }
        }
    }

    if (requiredType != null) {
        try {
            return beanContext.getBean(requiredType, Qualifiers.byName(name));
        } catch (NoSuchBeanException e) {
            throw new NoSuchBeanDefinitionException(name);
        }
    } else {
        throw new NoSuchBeanDefinitionException(name);
    }
}
 
Example #20
Source File: EntitiesInPackageCondition.java    From micronaut-sql with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(ConditionContext context) {
    final AnnotationMetadataProvider component = context.getComponent();
    if (component instanceof BeanDefinition) {
        BeanDefinition<?> definition = (BeanDefinition<?>) component;
        final BeanContext beanContext = context.getBeanContext();
        if (beanContext instanceof ApplicationContext) {

            final Optional<String> name = definition instanceof NameResolver ? ((NameResolver) definition).resolveName() : Optional.empty();
            final Qualifier<JpaConfiguration> q = Qualifiers.byName(name.orElse("default"));
            final Optional<JpaConfiguration> jpaConfiguration = beanContext.findBean(JpaConfiguration.class, q);
            JpaConfiguration.EntityScanConfiguration entityScanConfig = jpaConfiguration.map(JpaConfiguration::getEntityScanConfiguration).orElse(null);

            if (entityScanConfig == null) {
                return false;
            }

            boolean isClasspathScanEnabled = entityScanConfig.isClasspath();
            String[] packagesToScan = entityScanConfig.getPackages();
            boolean hasEntitiesOnClassPath = false;
            boolean hasIntrospections = false;
            if (isClasspathScanEnabled) {
                final Environment environment = ((ApplicationContext) beanContext).getEnvironment();
                if (ArrayUtils.isNotEmpty(packagesToScan)) {
                    hasEntitiesOnClassPath = environment.scan(Entity.class, packagesToScan).findAny().isPresent();
                } else {
                    hasEntitiesOnClassPath = environment.scan(Entity.class).findAny().isPresent();
                }
            } else {
                if (ArrayUtils.isNotEmpty(packagesToScan)) {
                    hasIntrospections = !BeanIntrospector.SHARED
                            .findIntrospections(Entity.class, packagesToScan).isEmpty();
                } else {
                    hasIntrospections = !BeanIntrospector.SHARED
                            .findIntrospections(Entity.class).isEmpty();
                }
            }

            return hasEntitiesOnClassPath || hasIntrospections;
        }
    }
    return true;
}