Java Code Examples for org.springframework.context.support.GenericApplicationContext#registerBean()

The following examples show how to use org.springframework.context.support.GenericApplicationContext#registerBean() . 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: RedisPositionsConfiguration.java    From liiklus with MIT License 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    var type = environment.getRequiredProperty("storage.positions.type");
    if(!"REDIS".equals(type)) {
        return;
    }

    var redisProperties = PropertiesUtil.bind(environment, new RedisProperties());

    applicationContext.registerBean(RedisPositionsStorage.class, () -> {
        var redisURI = RedisURI.builder()
                .withHost(redisProperties.getHost())
                .withPort(redisProperties.getPort())
                .build();

        return new RedisPositionsStorage(
                Mono
                        .fromCompletionStage(() -> RedisClient.create().connectAsync(StringCodec.UTF8, redisURI))
                        .cache(),
                redisProperties.getPositionsProperties().getPrefix()
        );
    });
}
 
Example 2
Source File: PluginListenerFactory.java    From springboot-plugin-framework-parent with Apache License 2.0 5 votes vote down vote up
public <T extends PluginListener> void buildListenerClass(GenericApplicationContext applicationContext){
    if(applicationContext == null){
        return;
    }
    synchronized (listenerClasses){
        for (Class<T> listenerClass : listenerClasses) {
            applicationContext.registerBean(listenerClass);
            T bean = applicationContext.getBean(listenerClass);
            listeners.add(bean);
        }
        listenerClasses.clear();
    }
}
 
Example 3
Source File: ConfigurationClassProcessingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Autowired
void register(GenericApplicationContext ctx) {
	ctx.registerBean("spouse", TestBean.class,
			() -> new TestBean("functional"));
	Supplier<TestBean> testBeanSupplier = () -> new TestBean(ctx.getBean("spouse", TestBean.class));
	ctx.registerBean(TestBean.class,
			testBeanSupplier,
			bd -> bd.setPrimary(true));
}
 
Example 4
Source File: TestModuleInitializer.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	if (!ClassUtils.isPresent("org.springframework.boot.test.context.ImportsContextCustomizer",
			context.getClassLoader())
			|| !context.getEnvironment().getProperty("spring.functional.enabled", Boolean.class, true)) {
		// Only used in tests - could move to separate jar
		return;
	}
	ImportRegistrars registrars;
	// TODO: extract this logic and share with FunctionalInstallerListener?
	if (!context.getBeanFactory().containsSingleton(ConditionService.class.getName())) {
		if (!context.getBeanFactory().containsSingleton(MetadataReaderFactory.class.getName())) {
			context.getBeanFactory().registerSingleton(MetadataReaderFactory.class.getName(),
					new CachingMetadataReaderFactory(context.getClassLoader()));
		}
		context.getBeanFactory().registerSingleton(ConditionService.class.getName(),
				new SimpleConditionService(context, context.getBeanFactory(), context.getEnvironment(), context));
		registrars = new FunctionalInstallerImportRegistrars(context);
		context.registerBean(ImportRegistrars.class, () -> registrars);
	}
	else {
		registrars = context.getBean(ImportRegistrars.class.getName(), ImportRegistrars.class);
	}
	for (String name : context.getBeanFactory().getBeanDefinitionNames()) {
		BeanDefinition definition = context.getBeanFactory().getBeanDefinition(name);
		if (definition.getBeanClassName().contains("ImportsContextCustomizer$ImportsConfiguration")) {
			SimpleConditionService.EXCLUDES_ENABLED = true;
			Class<?> testClass = (definition != null) ? (Class<?>) definition.getAttribute("testClass") : null;
			if (testClass != null) {
				Set<Import> merged = AnnotatedElementUtils.findAllMergedAnnotations(testClass, Import.class);
				for (Import ann : merged) {
					for (Class<?> imported : ann.value()) {
						registrars.add(testClass, imported);
					}
				}
			}
		}
	}
}
 
Example 5
Source File: RSocketConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    var serverProperties = PropertiesUtil.bind(environment, new RSocketServerProperties());

    if (!serverProperties.isEnabled()) {
        return;
    }

    applicationContext.registerBean(RSocketLiiklusService.class);

    applicationContext.registerBean(
            CloseableChannel.class,
            () -> {
                var liiklusService = applicationContext.getBean(LiiklusService.class);

                return RSocketFactory.receive()
                        .acceptor((setup, sendingSocket) -> Mono.just(new RequestHandlingRSocket(new LiiklusServiceServer(liiklusService, Optional.empty(), Optional.empty()))))
                        .transport(TcpServerTransport.create(serverProperties.getHost(), serverProperties.getPort()))
                        .start()
                        .block();
            },
            it -> {
                it.setDestroyMethodName("dispose");
            }
    );
}
 
Example 6
Source File: ContextFunctionCatalogInitializerTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("function", FunctionRegistration.class,
			() -> new FunctionRegistration<>(function()).type(
					FunctionType.from(String.class).to(String.class).getType()));
	context.registerBean(ValueConfiguration.class, () -> this);
}
 
Example 7
Source File: ReactiveWebServerInitializer.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class, WebServerFactoryCustomizerBeanPostProcessor::new);

	context.registerBean(ReactiveWebServerFactoryCustomizer.class, () -> new ReactiveWebServerFactoryCustomizer(this.serverProperties));
	context.registerBean(ConfigurableReactiveWebServerFactory.class, () -> serverFactory);
	//noinspection deprecation
	context.registerBean(ErrorAttributes.class, () -> new DefaultErrorAttributes(serverProperties.getError().isIncludeException()));
	context.registerBean(ErrorWebExceptionHandler.class,  () -> {
		ErrorWebFluxAutoConfiguration errorConfiguration = new ErrorWebFluxAutoConfiguration(this.serverProperties);
		return errorConfiguration.errorWebExceptionHandler(context.getBean(ErrorAttributes.class), this.resourceProperties, context.getBeanProvider(ViewResolver.class), context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class), context);
	});
	context.registerBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class, () -> new EnableWebFluxConfigurationWrapper(context, webFluxProperties));
	context.registerBean(LOCALE_CONTEXT_RESOLVER_BEAN_NAME, LocaleContextResolver.class, () -> context.getBean(EnableWebFluxConfigurationWrapper.class).localeContextResolver());
	context.registerBean("responseStatusExceptionHandler", WebExceptionHandler.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).responseStatusExceptionHandler());

	context.registerBean(RouterFunctionMapping.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).routerFunctionMapping(context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class)));
	context.registerBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).serverCodecConfigurer());
	context.registerBean("webFluxAdapterRegistry", ReactiveAdapterRegistry.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxAdapterRegistry());
	context.registerBean("handlerFunctionAdapter", HandlerFunctionAdapter.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).handlerFunctionAdapter());
	context.registerBean("webFluxContentTypeResolver", RequestedContentTypeResolver.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxContentTypeResolver());
	context.registerBean("webFluxConversionService", FormattingConversionService.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxConversionService());
	context.registerBean("serverResponseResultHandler", ServerResponseResultHandler.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).serverResponseResultHandler(context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class)));
	context.registerBean("simpleHandlerAdapter", SimpleHandlerAdapter.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).simpleHandlerAdapter());
	context.registerBean("viewResolutionResultHandler", ViewResolutionResultHandler.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).viewResolutionResultHandler(context.getBean("webFluxAdapterRegistry", ReactiveAdapterRegistry.class), context.getBean("webFluxContentTypeResolver", RequestedContentTypeResolver.class)));
	context.registerBean("webFluxValidator", Validator.class, () -> context.getBean("fuWebFluxConfiguration", EnableWebFluxConfigurationWrapper.class).webFluxValidator());
	context.registerBean(HttpHandler.class, () -> applicationContext(context).build());
	context.registerBean(WEB_HANDLER_BEAN_NAME, DispatcherHandler.class, (Supplier<DispatcherHandler>) DispatcherHandler::new);
	context.registerBean(WebFluxConfig.class, () -> new WebFluxConfig(resourceProperties, webFluxProperties, context, context.getBeanProvider(HandlerMethodArgumentResolver.class), context.getBeanProvider(CodecCustomizer.class),
		context.getBeanProvider(ResourceHandlerRegistrationCustomizer.class), context.getBeanProvider(ViewResolver.class)));
}
 
Example 8
Source File: FunctionExporterInitializer.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
private void registerWebClient(GenericApplicationContext context) {
	if (ClassUtils.isPresent("org.springframework.web.reactive.function.client.WebClient",
			getClass().getClassLoader())) {
		if (context.getBeanFactory().getBeanNamesForType(WebClient.Builder.class, false, false).length == 0) {
			context.registerBean(WebClient.Builder.class, () -> WebClient.builder());
		}
	}
}
 
Example 9
Source File: LettuceRedisInitializer.java    From spring-fu with Apache License 2.0 4 votes vote down vote up
@Override
  public void initialize(GenericApplicationContext context) {
context.registerBean(RedisConnectionFactory.class, () -> getLettuceConnectionFactory(context));
context.registerBean(ReactiveRedisConnectionFactory.class, () -> getLettuceConnectionFactory(context));
  }
 
Example 10
Source File: FunctionalSpringApplication.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
private void register(GenericApplicationContext context, Object function, Class<?> functionType) {
	context.registerBean("function", FunctionRegistration.class,
			() -> new FunctionRegistration<>(
					handler(context, function, functionType))
							.type(FunctionType.of(functionType)));
}
 
Example 11
Source File: ReactiveWebClientBuilderInitializer.java    From spring-fu with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean(WebClient.Builder.class, () -> new WebClientAutoConfiguration().webClientBuilder(context.getBeanProvider(WebClientCustomizer.class)));
	context.registerBean(DefaultWebClientCodecCustomizer.class, () -> new DefaultWebClientCodecCustomizer(this.baseUrl, new ArrayList<>(context.getBeansOfType(CodecCustomizer.class).values())));
}
 
Example 12
Source File: ContextFunctionCatalogInitializerTests.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("gson", Gson.class, this::gson);
	context.registerBean(GsonConfiguration.class, () -> this);
}
 
Example 13
Source File: StringConverterInitializer.java    From spring-fu with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("StringHttpMessageConverter", HttpMessageConverter.class, (Supplier<HttpMessageConverter>) StringHttpMessageConverter::new);
}
 
Example 14
Source File: ExamplePluginConfiguration.java    From liiklus with MIT License 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    applicationContext.registerBean(ExampleRecordPreProcessor.class);
    applicationContext.registerBean(ExampleRecordPostProcessor.class);
}
 
Example 15
Source File: RssConverterInitializer.java    From spring-fu with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("rssChannelHttpMessageConverter", HttpMessageConverter.class, RssChannelHttpMessageConverter::new);
}
 
Example 16
Source File: ListenerContainerConfiguration.java    From rocketmq-spring with Apache License 2.0 4 votes vote down vote up
private void registerContainer(String beanName, Object bean) {
    Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

    if (RocketMQListener.class.isAssignableFrom(bean.getClass()) && RocketMQReplyListener.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " cannot be both instance of " + RocketMQListener.class.getName() + " and " + RocketMQReplyListener.class.getName());
    }

    if (!RocketMQListener.class.isAssignableFrom(bean.getClass()) && !RocketMQReplyListener.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " is not instance of " + RocketMQListener.class.getName() + " or " + RocketMQReplyListener.class.getName());
    }

    RocketMQMessageListener annotation = clazz.getAnnotation(RocketMQMessageListener.class);

    String consumerGroup = this.environment.resolvePlaceholders(annotation.consumerGroup());
    String topic = this.environment.resolvePlaceholders(annotation.topic());

    boolean listenerEnabled =
        (boolean) rocketMQProperties.getConsumer().getListeners().getOrDefault(consumerGroup, Collections.EMPTY_MAP)
            .getOrDefault(topic, true);

    if (!listenerEnabled) {
        log.debug(
            "Consumer Listener (group:{},topic:{}) is not enabled by configuration, will ignore initialization.",
            consumerGroup, topic);
        return;
    }
    validate(annotation);

    String containerBeanName = String.format("%s_%s", DefaultRocketMQListenerContainer.class.getName(),
        counter.incrementAndGet());
    GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext;

    genericApplicationContext.registerBean(containerBeanName, DefaultRocketMQListenerContainer.class,
        () -> createRocketMQListenerContainer(containerBeanName, bean, annotation));
    DefaultRocketMQListenerContainer container = genericApplicationContext.getBean(containerBeanName,
        DefaultRocketMQListenerContainer.class);
    if (!container.isRunning()) {
        try {
            container.start();
        } catch (Exception e) {
            log.error("Started container failed. {}", container, e);
            throw new RuntimeException(e);
        }
    }

    log.info("Register the listener to container, listenerBeanName:{}, containerBeanName:{}", beanName, containerBeanName);
}
 
Example 17
Source File: FunctionEndpointInitializer.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
private void registerWebFluxAutoConfiguration(GenericApplicationContext context) {
	context.registerBean(DefaultErrorWebExceptionHandler.class, () -> errorHandler(context));
	context.registerBean(WebHttpHandlerBuilder.WEB_HANDLER_BEAN_NAME, HttpWebHandlerAdapter.class,
			() -> httpHandler(context));
	context.addApplicationListener(new ServerListener(context));
}
 
Example 18
Source File: SentinelInitializer.java    From spring-fu with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
    if (sentinel != null) {
        context.registerBean(RedisSentinelConfiguration.class, this::getRedisSentinelConfiguration);
    }
}
 
Example 19
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@Override
protected MessageHandler createProducerMessageHandler(
		final ProducerDestination producerDestination,
		ExtendedProducerProperties<RabbitProducerProperties> producerProperties,
		MessageChannel errorChannel) {
	Assert.state(
			!HeaderMode.embeddedHeaders.equals(producerProperties.getHeaderMode()),
			"the RabbitMQ binder does not support embedded headers since RabbitMQ supports headers natively");
	String prefix = producerProperties.getExtension().getPrefix();
	String exchangeName = producerDestination.getName();
	String destination = StringUtils.isEmpty(prefix) ? exchangeName
			: exchangeName.substring(prefix.length());
	final AmqpOutboundEndpoint endpoint = new AmqpOutboundEndpoint(
			buildRabbitTemplate(producerProperties.getExtension(),
					errorChannel != null));
	endpoint.setExchangeName(producerDestination.getName());
	RabbitProducerProperties extendedProperties = producerProperties.getExtension();
	boolean expressionInterceptorNeeded = expressionInterceptorNeeded(
			extendedProperties);
	Expression routingKeyExpression = extendedProperties.getRoutingKeyExpression();
	if (!producerProperties.isPartitioned()) {
		if (routingKeyExpression == null) {
			endpoint.setRoutingKey(destination);
		}
		else {
			if (expressionInterceptorNeeded) {
				endpoint.setRoutingKeyExpressionString("headers['"
						+ RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER
						+ "']");
			}
			else {
				endpoint.setRoutingKeyExpression(routingKeyExpression);
			}
		}
	}
	else {
		if (routingKeyExpression == null) {
			endpoint.setRoutingKeyExpression(
					buildPartitionRoutingExpression(destination, false));
		}
		else {
			if (expressionInterceptorNeeded) {
				endpoint.setRoutingKeyExpression(
						buildPartitionRoutingExpression("headers['"
								+ RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER
								+ "']", true));
			}
			else {
				endpoint.setRoutingKeyExpression(buildPartitionRoutingExpression(
						routingKeyExpression.getExpressionString(), true));
			}
		}
	}
	if (extendedProperties.getDelayExpression() != null) {
		if (expressionInterceptorNeeded) {
			endpoint.setDelayExpressionString("headers['"
					+ RabbitExpressionEvaluatingInterceptor.DELAY_HEADER + "']");
		}
		else {
			endpoint.setDelayExpression(extendedProperties.getDelayExpression());
		}
	}
	DefaultAmqpHeaderMapper mapper = DefaultAmqpHeaderMapper.outboundMapper();
	List<String> headerPatterns = new ArrayList<>(extendedProperties.getHeaderPatterns().length + 3);
	headerPatterns.add("!" + BinderHeaders.PARTITION_HEADER);
	headerPatterns.add("!" + IntegrationMessageHeaderAccessor.SOURCE_DATA);
	headerPatterns.add("!" + IntegrationMessageHeaderAccessor.DELIVERY_ATTEMPT);
	headerPatterns.addAll(Arrays.asList(extendedProperties.getHeaderPatterns()));
	mapper.setRequestHeaderNames(
			headerPatterns.toArray(new String[headerPatterns.size()]));
	endpoint.setHeaderMapper(mapper);
	endpoint.setDefaultDeliveryMode(extendedProperties.getDeliveryMode());
	endpoint.setBeanFactory(this.getBeanFactory());
	if (errorChannel != null) {
		checkConnectionFactoryIsErrorCapable();
		endpoint.setReturnChannel(errorChannel);
		endpoint.setConfirmNackChannel(errorChannel);
		String ackChannelBeanName = StringUtils
				.hasText(extendedProperties.getConfirmAckChannel())
						? extendedProperties.getConfirmAckChannel()
						: IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME;
		if (!ackChannelBeanName.equals(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)
				&& !getApplicationContext().containsBean(ackChannelBeanName)) {
			GenericApplicationContext context = (GenericApplicationContext) getApplicationContext();
			context.registerBean(ackChannelBeanName, DirectChannel.class,
					() -> new DirectChannel());
		}
		endpoint.setConfirmAckChannelName(ackChannelBeanName);
		endpoint.setConfirmCorrelationExpressionString("#root");
		endpoint.setErrorMessageStrategy(new DefaultErrorMessageStrategy());
	}
	endpoint.setHeadersMappedLast(true);
	return endpoint;
}
 
Example 20
Source File: DemoApplication.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	context.registerBean("foobar", FunctionRegistration.class,
			() -> new FunctionRegistration<>(new Foobar()).type(
					FunctionType.from(String.class).to(String.class)));
}