io.micronaut.inject.qualifiers.Qualifiers Java Examples
The following examples show how to use
io.micronaut.inject.qualifiers.Qualifiers.
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: GrpcChannelBuilderFactory.java From micronaut-grpc with Apache License 2.0 | 6 votes |
/** * Constructor a managed channel build for the given target name and interceptors. * @param target The target name * @param interceptors The interceptors * @return The channel builder */ @Bean @Prototype protected NettyChannelBuilder managedChannelBuilder(@Parameter String target, List<ClientInterceptor> interceptors) { GrpcManagedChannelConfiguration config = beanContext.findBean(GrpcManagedChannelConfiguration.class, Qualifiers.byName(target)).orElseGet(() -> { final GrpcDefaultManagedChannelConfiguration mcc = new GrpcDefaultManagedChannelConfiguration( target, beanContext.getEnvironment(), executorService ); beanContext.inject(mcc); return mcc; } ); final NettyChannelBuilder channelBuilder = config.getChannelBuilder(); if (CollectionUtils.isNotEmpty(interceptors)) { channelBuilder.intercept(interceptors); } return channelBuilder; }
Example #2
Source File: GrpcChannelBuilderFactory.java From micronaut-grpc with Apache License 2.0 | 6 votes |
/** * Constructor a managed channel build for the given target name and interceptors. * @param target The target name * @param interceptors The interceptors * @return The channel builder */ @Bean @Prototype protected NettyChannelBuilder managedChannelBuilder(@Parameter String target, List<ClientInterceptor> interceptors) { GrpcManagedChannelConfiguration config = beanContext.findBean(GrpcManagedChannelConfiguration.class, Qualifiers.byName(target)).orElseGet(() -> { final GrpcDefaultManagedChannelConfiguration mcc = new GrpcDefaultManagedChannelConfiguration( target, beanContext.getEnvironment(), executorService ); beanContext.inject(mcc); return mcc; } ); final NettyChannelBuilder channelBuilder = config.getChannelBuilder(); if (CollectionUtils.isNotEmpty(interceptors)) { channelBuilder.intercept(interceptors); } return channelBuilder; }
Example #3
Source File: DataEntityManagerFactoryBean.java From micronaut-data with Apache License 2.0 | 6 votes |
/** * Builds the {@link StandardServiceRegistry} bean for the given {@link DataSource}. * * @param dataSourceName The data source name * @param dataSource The data source * @return The {@link StandardServiceRegistry} */ @EachBean(DataSource.class) @Replaces( factory = io.micronaut.configuration.hibernate.jpa.EntityManagerFactoryBean.class, bean = StandardServiceRegistry.class) @Requires(missingClasses = "org.springframework.orm.hibernate5.HibernateTransactionManager") protected StandardServiceRegistry hibernateStandardServiceRegistry( @Parameter String dataSourceName, DataSource dataSource) { if (dataSource instanceof DelegatingDataSource) { dataSource = ((DelegatingDataSource) dataSource).getTargetDataSource(); } Map<String, Object> additionalSettings = new LinkedHashMap<>(); additionalSettings.put(AvailableSettings.DATASOURCE, dataSource); additionalSettings.put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, MicronautSessionContext.class.getName()); additionalSettings.put(AvailableSettings.SESSION_FACTORY_NAME, dataSourceName); additionalSettings.put(AvailableSettings.SESSION_FACTORY_NAME_IS_JNDI, false); JpaConfiguration jpaConfiguration = beanLocator.findBean(JpaConfiguration.class, Qualifiers.byName(dataSourceName)) .orElse(this.jpaConfiguration); return jpaConfiguration.buildStandardServiceRegistry( additionalSettings ); }
Example #4
Source File: AbstractFlywayMigration.java From micronaut-flyway with Apache License 2.0 | 6 votes |
/** * Configure the Flyway runner for a specific configuration and a dataSource. * * @param config The {@link FlywayConfigurationProperties} * @param dataSource The {@link DataSource} */ void run(FlywayConfigurationProperties config, DataSource dataSource) { if (config.isEnabled()) { FluentConfiguration fluentConfiguration = config.getFluentConfiguration(); fluentConfiguration.dataSource(dataSource); Flyway flyway = fluentConfiguration.load(); this.applicationContext.registerSingleton(Flyway.class, flyway, Qualifiers.byName(config.getNameQualifier()), false); if (config.isAsync()) { runAsync(config, flyway); } else { runFlyway(config, flyway); } } }
Example #5
Source File: FlywayEndpoint.java From micronaut-flyway with Apache License 2.0 | 6 votes |
/** * @return A list of Flyway migrations per active configuration */ @Read public Publisher<FlywayReport> flywayMigrations() { return Flowable.fromIterable(flywayConfigurationProperties) .filter(FlywayConfigurationProperties::isEnabled) .map(c -> new Pair<>(c, applicationContext .findBean(Flyway.class, Qualifiers.byName(c.getNameQualifier())) .orElse(null))) .filter(pair -> pair.getSecond() != null) .map(pair -> new FlywayReport( pair.getFirst().getNameQualifier(), Arrays.asList(pair.getSecond().info().all())) ); }
Example #6
Source File: AlternativeMigrationRunner.java From micronaut-flyway with Apache License 2.0 | 6 votes |
@Override public FlywayConfigurationProperties onCreated(BeanCreatedEvent<FlywayConfigurationProperties> event) { FlywayConfigurationProperties config = event.getBean(); String name = config.getNameQualifier(); if (config.isEnabled()) { if (config.hasAlternativeDatabaseConfiguration()) { DataSource dataSource = new DriverDataSource(Thread.currentThread().getContextClassLoader(), null, config.getUrl(), config.getUser(), config.getPassword()); run(config, dataSource); } else { if (!applicationContext.containsBean(DataSource.class, Qualifiers.byName(name))) { if (LOG.isDebugEnabled()) { LOG.debug("* Flyway bean not created for identifier [" + name + "] because no data source was found with a named qualifier of the same name."); } } } } return config; }
Example #7
Source File: DataSourceMigrationRunner.java From micronaut-flyway with Apache License 2.0 | 6 votes |
@Override public DataSource onCreated(BeanCreatedEvent<DataSource> event) { DataSource dataSource = dataSourceResolver.resolve(event.getBean()); if (event.getBeanDefinition() instanceof NameResolver) { ((NameResolver) event.getBeanDefinition()) .resolveName() .ifPresent(name -> { applicationContext .findBean(FlywayConfigurationProperties.class, Qualifiers.byName(name)) .ifPresent(flywayConfig -> run(flywayConfig, dataSource)); }); } return dataSource; }
Example #8
Source File: GormMigrationRunner.java From micronaut-flyway with Apache License 2.0 | 5 votes |
@Override public HibernateDatastore onCreated(BeanCreatedEvent<HibernateDatastore> event) { HibernateDatastore hibernateDatastore = event.getBean(); hibernateDatastore.getConnectionSources().forEach(connectionSource -> { String qualifier = connectionSource.getName(); DataSource dataSource = ((HibernateConnectionSource) connectionSource).getDataSource(); applicationContext .findBean(FlywayConfigurationProperties.class, Qualifiers.byName(qualifier)) .ifPresent(flywayConfig -> run(flywayConfig, dataSource)); }); return hibernateDatastore; }
Example #9
Source File: DBUnitExtension.java From database-rider with Apache License 2.0 | 5 votes |
private static DataSource getDataSourceFromMicronautContext(ExtensionContext extensionContext, String beanName) { Optional<io.micronaut.context.ApplicationContext> context = getMicronautApplicationContext(extensionContext); if (context.isPresent()) { return beanName.isEmpty() ? context.get().getBean(DataSource.class) : context.get().getBean(DataSource.class, Qualifiers.byName(beanName)); } throw new RuntimeException("Micronaut context is not available for test: " + extensionContext.getTestClass().get().getName()); }
Example #10
Source File: MicronautBeanFactory.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public void registerSingleton(String beanName, Object singletonObject) { final Class type = singletonObject.getClass(); beanContext.registerSingleton( type, singletonObject, Qualifiers.byName(beanName) ); super.registerSingleton(beanName, singletonObject); }
Example #11
Source File: MicronautBeanFactory.java From micronaut-spring with Apache License 2.0 | 5 votes |
@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 #12
Source File: TransactionInterceptor.java From micronaut-spring with Apache License 2.0 | 5 votes |
private PlatformTransactionManager resolveTransactionManager(String transactionManagerName) { try { if (transactionManagerName != null) { return this.transactionManagerMap.computeIfAbsent(transactionManagerName, s -> beanLocator.getBean(PlatformTransactionManager.class, Qualifiers.byName(transactionManagerName)) ); } else { return this.transactionManagerMap.computeIfAbsent("default", s -> beanLocator.getBean(PlatformTransactionManager.class) ); } } catch (NoSuchBeanException e) { throw new TransactionSystemException("No transaction manager configured" + (transactionManagerName != null ? " for name: " + transactionManagerName : "")); } }
Example #13
Source File: GrpcChannelScope.java From micronaut-grpc with Apache License 2.0 | 5 votes |
@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: MicronautLambdaContainerHandler.java From micronaut-aws with Apache License 2.0 | 5 votes |
@Override public void initialize() throws ContainerInitializationException { Timer.start(TIMER_INIT); try { this.applicationContext = applicationContextBuilder.environments( Environment.FUNCTION, MicronautLambdaContext.ENVIRONMENT_LAMBDA) .build() .start(); this.lambdaContainerEnvironment.setApplicationContext(applicationContext); this.lambdaContainerEnvironment.setJsonCodec(applicationContext.getBean(JsonMediaTypeCodec.class)); this.lambdaContainerEnvironment.setRouter(applicationContext.getBean(Router.class)); Optional<ObjectMapper> objectMapper = applicationContext.findBean(ObjectMapper.class, Qualifiers.byName("aws")); if (objectMapper.isPresent()) { lambdaContainerEnvironment.setObjectMapper(objectMapper.get()); } else { lambdaContainerEnvironment.setObjectMapper(applicationContext.getBean(ObjectMapper.class)); } this.requestArgumentSatisfier = new RequestArgumentSatisfier( applicationContext.getBean(RequestBinderRegistry.class) ); this.resourceResolver = applicationContext.getBean(StaticResourceResolver.class); } catch (Exception e) { throw new ContainerInitializationException( "Error starting Micronaut container: " + e.getMessage(), e ); } Timer.stop(TIMER_INIT); }
Example #15
Source File: MicronautJunit5Extension.java From micronaut-test with Apache License 2.0 | 5 votes |
@Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { Named named = parameterContext.findAnnotation(Named.class).orElse(null); if (named != null) { return applicationContext.getBean(parameterContext.getParameter().getType(), Qualifiers.byName(named.value())); } else { return applicationContext.getBean(parameterContext.getParameter().getType()); } }
Example #16
Source File: TransactionAwareDataSource.java From micronaut-data with Apache License 2.0 | 5 votes |
private Connection getTransactionAwareConnection() { if (transactionAwareConnection == null) { transactionAwareConnection = beanLocator.getBean(Connection.class, Qualifiers.byName(qualifier)); } return transactionAwareConnection; }
Example #17
Source File: DefaultJdbcRepositoryOperations.java From micronaut-data with Apache License 2.0 | 5 votes |
/** * 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 #18
Source File: DataIntroductionAdvice.java From micronaut-data with Apache License 2.0 | 5 votes |
private @NonNull DataInterceptor<Object, Object> findInterceptor( @Nullable String dataSourceName, @NonNull Class<?> operationsType, @NonNull Class<?> interceptorType) { DataInterceptor interceptor; if (!RepositoryOperations.class.isAssignableFrom(operationsType)) { throw new IllegalArgumentException("Repository type must be an instance of RepositoryOperations!"); } RepositoryOperations datastore; try { if (dataSourceName != null) { Qualifier qualifier = Qualifiers.byName(dataSourceName); datastore = (RepositoryOperations) beanLocator.getBean(operationsType, qualifier); } else { datastore = (RepositoryOperations) beanLocator.getBean(operationsType); } } catch (NoSuchBeanException e) { throw new ConfigurationException("No backing RepositoryOperations configured for repository. Check your configuration and try again", e); } BeanIntrospection<Object> introspection = BeanIntrospector.SHARED.findIntrospections(ref -> interceptorType.isAssignableFrom(ref.getBeanType())).stream().findFirst().orElseThrow(() -> new DataAccessException("No Data interceptor found for type: " + interceptorType) ); if (introspection.getConstructorArguments().length == 0) { interceptor = (DataInterceptor) introspection.instantiate(); } else { interceptor = (DataInterceptor) introspection.instantiate(datastore); } return interceptor; }
Example #19
Source File: GrpcChannelScope.java From micronaut-grpc with Apache License 2.0 | 5 votes |
@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 #20
Source File: KafkaClientScope.java From micronaut-kafka with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private <T> T getKafkaProducer(@Nullable String id, Argument<?> keyType, Argument<?> valueType) { ClientKey key = new ClientKey( id, keyType.getType(), valueType.getType() ); return (T) clients.computeIfAbsent(key, clientKey -> { Supplier<AbstractKafkaProducerConfiguration> defaultResolver = () -> beanContext.getBean(AbstractKafkaProducerConfiguration.class); AbstractKafkaProducerConfiguration config; boolean hasId = StringUtils.isNotEmpty(id); if (hasId) { config = beanContext.findBean( AbstractKafkaProducerConfiguration.class, Qualifiers.byName(id) ).orElseGet(defaultResolver); } else { config = defaultResolver.get(); } DefaultKafkaProducerConfiguration newConfig = new DefaultKafkaProducerConfiguration(config); Properties properties = newConfig.getConfig(); if (!properties.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) { Serializer<?> keySerializer = serdeRegistry.pickSerializer(keyType); newConfig.setKeySerializer(keySerializer); } if (!properties.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) { Serializer<?> valueSerializer = serdeRegistry.pickSerializer(valueType); newConfig.setValueSerializer(valueSerializer); } if (hasId) { properties.putIfAbsent(ProducerConfig.CLIENT_ID_CONFIG, id); } return beanContext.createBean(Producer.class, newConfig); }); }
Example #21
Source File: MicronautBeanProcessor.java From micronaut-spring with Apache License 2.0 | 4 votes |
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (environment != null) { String[] profiles = getProfiles(); micronautContext = new DefaultApplicationContext(profiles) { DefaultEnvironment env = new DefaultEnvironment(() -> Arrays.asList(profiles)) { @Override public io.micronaut.context.env.Environment start() { return this; } @Override public io.micronaut.context.env.Environment stop() { return this; } @Override public boolean containsProperty(String name) { return environment.containsProperty(name); } @Override public boolean containsProperties(String name) { return environment.containsProperty(name); } @Override public <T> Optional<T> getProperty(String name, ArgumentConversionContext<T> conversionContext) { return Optional.ofNullable(environment.getProperty(name, conversionContext.getArgument().getType())); } }; @Override public io.micronaut.context.env.Environment getEnvironment() { return env; } }; } else { micronautContext = new DefaultApplicationContext(); } micronautContext.start(); micronautBeanQualifierTypes .forEach(micronautBeanQualifierType -> { Qualifier<Object> micronautBeanQualifier; if (micronautBeanQualifierType.isAnnotation()) { micronautBeanQualifier = Qualifiers.byStereotype((Class<? extends Annotation>) micronautBeanQualifierType); } else { micronautBeanQualifier = Qualifiers.byType(micronautBeanQualifierType); } micronautContext.getBeanDefinitions(micronautBeanQualifier) .forEach(definition -> { final BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder .rootBeanDefinition(MicronautSpringBeanFactory.class.getName()); beanDefinitionBuilder.addPropertyValue(MICRONAUT_BEAN_TYPE_PROPERTY_NAME, definition.getBeanType()); beanDefinitionBuilder.addPropertyValue(MICRONAUT_CONTEXT_PROPERTY_NAME, micronautContext); beanDefinitionBuilder.addPropertyValue(MICRONAUT_SINGLETON_PROPERTY_NAME, definition.isSingleton()); ((DefaultListableBeanFactory) beanFactory).registerBeanDefinition(definition.getName(), beanDefinitionBuilder.getBeanDefinition()); }); }); }
Example #22
Source File: JooqConfigurationFactory.java From micronaut-sql with Apache License 2.0 | 4 votes |
/** * Creates jOOQ {@link Configuration}. * It will configure it with available jOOQ provider beans with the same qualifier. * * @param name The data source name * @param dataSource The {@link DataSource} * @param transactionProvider The transaction provider * @param settings The settings * @param executorProvider The executor provider * @param recordMapperProvider The record mapper provider * @param recordUnmapperProvider The record unmapper provider * @param metaProvider The metadata provider * @param ctx The {@link ApplicationContext} * @return A {@link Configuration} */ @EachBean(DataSource.class) public Configuration jooqConfiguration( @Parameter String name, DataSource dataSource, @Parameter @Nullable TransactionProvider transactionProvider, @Parameter @Nullable Settings settings, @Parameter @Nullable ExecutorProvider executorProvider, @Parameter @Nullable RecordMapperProvider recordMapperProvider, @Parameter @Nullable RecordUnmapperProvider recordUnmapperProvider, @Parameter @Nullable MetaProvider metaProvider, ApplicationContext ctx ) { DefaultConfiguration configuration = new DefaultConfiguration(); JooqConfigurationProperties properties = ctx.findBean(JooqConfigurationProperties.class, Qualifiers.byName(name)) .orElseGet(JooqConfigurationProperties::new); DataSourceResolver dataSourceResolver = ctx.findBean(DataSourceResolver.class).orElse(DataSourceResolver.DEFAULT); configuration.setSQLDialect(properties.determineSqlDialect(dataSourceResolver.resolve(dataSource))); configuration.setDataSource(dataSource); if (transactionProvider != null) { configuration.setTransactionProvider(transactionProvider); } if (settings != null) { configuration.setSettings(settings); } if (executorProvider != null) { configuration.setExecutorProvider(executorProvider); } if (recordMapperProvider != null) { configuration.setRecordMapperProvider(recordMapperProvider); } if (recordUnmapperProvider != null) { configuration.setRecordUnmapperProvider(recordUnmapperProvider); } if (metaProvider != null) { configuration.setMetaProvider(metaProvider); } configuration.setExecuteListenerProvider(ctx.getBeansOfType(ExecuteListenerProvider.class, Qualifiers.byName(name)) .toArray(new ExecuteListenerProvider[0])); configuration.setRecordListenerProvider(ctx.getBeansOfType(RecordListenerProvider.class, Qualifiers.byName(name)) .toArray(new RecordListenerProvider[0])); configuration.setVisitListenerProvider(ctx.getBeansOfType(VisitListenerProvider.class, Qualifiers.byName(name)) .toArray(new VisitListenerProvider[0])); configuration.setTransactionListenerProvider(ctx.getBeansOfType(TransactionListenerProvider.class, Qualifiers.byName(name)) .toArray(new TransactionListenerProvider[0])); configuration.setDiagnosticsListenerProvider(ctx.getBeansOfType(DiagnosticsListenerProvider.class, Qualifiers.byName(name)) .toArray(new DiagnosticsListenerProvider[0])); return configuration; }
Example #23
Source File: MicronautBeanFactory.java From micronaut-spring with Apache License 2.0 | 4 votes |
@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 #24
Source File: EntitiesInPackageCondition.java From micronaut-sql with Apache License 2.0 | 4 votes |
@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; }