Java Code Examples for org.springframework.boot.autoconfigure.condition.ConditionalOnClass

The following examples show how to use org.springframework.boot.autoconfigure.condition.ConditionalOnClass. These examples are extracted from open source projects. 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
@Lazy
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(CamelContext.class)
public CamelReactiveStreamsService camelReactiveStreamsService(ApplicationContext ac) throws Exception {
    ReactiveStreamsEngineConfiguration engineConfiguration = new ReactiveStreamsEngineConfiguration();

    if (configuration.getReactiveStreamsEngineConfiguration() != null) {
        engineConfiguration = ac.getBean(configuration.getReactiveStreamsEngineConfiguration(), ReactiveStreamsEngineConfiguration.class);
    } else {
        engineConfiguration.setThreadPoolName(configuration.getThreadPoolName());
        if (configuration.getThreadPoolMinSize() != null) {
            engineConfiguration.setThreadPoolMinSize(configuration.getThreadPoolMinSize());
        }
        if (configuration.getThreadPoolMaxSize() != null) {
            engineConfiguration.setThreadPoolMinSize(configuration.getThreadPoolMaxSize());
        }
    }

    return ReactiveStreamsHelper.resolveReactiveStreamsService(context, configuration.getServiceType(), engineConfiguration);
}
 
Example 2
/**
 * Build hibernate transaction manager.
 *
 * @param transactionManagerCustomizers transaction manager customizers
 * @return jpa transaction manager
 */
@Bean
@ConditionalOnMissingBean(PlatformTransactionManager.class)
@ConditionalOnClass(value = LocalContainerEntityManagerFactoryBean.class, name = "javax.persistence.EntityManager")
public PlatformTransactionManager jpaTransactionManager(final ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
    JpaTransactionManager result = new JpaTransactionManager();
    if (null != transactionManagerCustomizers.getIfAvailable()) {
        transactionManagerCustomizers.getIfAvailable().customize(result);
    }
    return result;
}
 
Example 3
@Bean
@ConditionalOnClass(DefaultMQProducer.class)
@ConditionalOnMissingBean(DefaultMQProducer.class)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = {"nameServer", "producer.group"})
public DefaultMQProducer mqProducer(RocketMQProperties rocketMQProperties) {

    RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
    String groupName = producerConfig.getGroup();
    Assert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");

    DefaultMQProducer producer = new DefaultMQProducer(producerConfig.getGroup());
    producer.setNamesrvAddr(rocketMQProperties.getNameServer());
    producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());

    return producer;
}
 
Example 4
Source Project: sofa-lookout   Source File: LookoutAutoConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * why use beanFactory to get DropWizardMetricsRegistry bean here?
 * because we do not want to import dropwizard dependencies indirectly!
 * let the application developer to decide whether or not to import.
 *
 * @return
 */
@Deprecated
@Bean
@ConditionalOnProperty(prefix = "com.alipay.sofa.lookout", name = "actuator-dropWizard-enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnClass(name = { "com.alipay.lookout.dropwizard.metrics.DropWizardMetricsRegistry",
        "com.codahale.metrics.MetricRegistry" })
public DropWizardMetricsRegistryFactory dropWizardMetricsRegistryFactory() {
    try {
        /*
         * In order to avoid [com.codahale.metrics.MetricRegistry] class not found.
         */
        com.codahale.metrics.MetricRegistry metricRegistry = beanFactory
            .getBean(com.codahale.metrics.MetricRegistry.class);
        if (metricRegistry == null) {
            logger
                .warn("spring boot actuator does not use dropwizard service,so lookout ignore dropwizard too!");
        } else {
            return new DropWizardMetricsRegistryFactory(metricRegistry);
        }
    } catch (NoClassDefFoundError e) {
        logger.debug("no dropwizard service found.");
    }
    return null;
}
 
Example 5
@Bean
@ConditionalOnBean(GrayTrackFilter.class)
@ConditionalOnClass(FilterRegistrationBean.class)
public FilterRegistrationBean grayTraceFilter(GrayTrackFilter filter) {
    GrayTrackProperties.Web webProperties = grayTrackProperties.getWeb();
    FilterRegistrationBean registration = new FilterRegistrationBean();
    //注入过滤器
    registration.setFilter(filter);
    //拦截规则
    for (String pattern : webProperties.getPathPatterns()) {
        registration.addUrlPatterns(pattern);
    }
    //过滤器名称
    registration.setName("GrayTrackFilter");
    //过滤器顺序
    registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
    return registration;
}
 
Example 6
Source Project: RestDoc   Source File: SpringSwagger2Configuration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnClass(FilterRegistrationBean.class)
@ConditionalOnMissingBean(RestDocConfig.HttpBasicAuth.class)
public FilterRegistrationBean<HttpBasicAuthFilter> swagger2HttpFilter(@Autowired(required = false) RestDocConfig restDocConfig) {
    RestDocConfig.HttpBasicAuth httpBasicAuth;
    if (restDocConfig == null || (httpBasicAuth = restDocConfig.getHttpBasicAuth()) == null)
        httpBasicAuth = new RestDocConfig.HttpBasicAuth(null, null);

    FilterRegistrationBean<HttpBasicAuthFilter> filterBean = new FilterRegistrationBean<>();
    HttpBasicAuthFilter authFilter = new HttpBasicAuthFilter(httpBasicAuth.getUsername(), httpBasicAuth.getPassword());
    filterBean.addUrlPatterns("/swagger2-ui/**","/swagger2.json","/swagger-ui/*","/swagger.json");
    filterBean.setFilter(authFilter);
    return filterBean;
}
 
Example 7
@Bean
@ConditionalOnClass(DefaultMQProducer.class)
@ConditionalOnMissingBean(DefaultMQProducer.class)
public DefaultMQProducer mqProducer() {
    DefaultMQProducer producer = new DefaultMQProducer();
    producer.setProducerGroup(rocketMqProperties.getProducerGroupName());
    producer.setNamesrvAddr(rocketMqProperties.getNameServer());

    producer.setSendMsgTimeout(rocketMqProperties.getProducerSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(rocketMqProperties.getProducerRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(rocketMqProperties.getProducerRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(rocketMqProperties.getProducerMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(rocketMqProperties.getProducerCompressMsgBodyOverHowMuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(rocketMqProperties.isProducerRetryAnotherBrokerWhenNotStoreOk());

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOGGER.info("producer shutdown");
        producer.shutdown();
        LOGGER.info("producer has shutdown");
    }));

    try {
        producer.start();
        LOGGER.info("rocketmq producer started, nameserver:{}, group:{}", rocketMqProperties.getNameServer(),
                rocketMqProperties.getProducerGroupName());
    } catch (MQClientException e) {
        LOGGER.error("producer start error, nameserver:{}, group:{}", rocketMqProperties.getNameServer(),
                rocketMqProperties.getProducerGroupName(), e);
    }

    return producer;
}
 
Example 8
/**
 * Creates a GrpcServerFactory using the non-shaded netty. This is the fallback, if the shaded one is not present.
 *
 * @param properties The properties used to configure the server.
 * @param serviceDiscoverer The discoverer used to identify the services that should be served.
 * @param serverConfigurers The server configurers that contain additional configuration for the server.
 * @return The shadedNettyGrpcServerFactory bean.
 */
@ConditionalOnMissingBean(ShadedNettyGrpcServerFactory.class)
@Conditional(ConditionalOnInterprocessServer.class)
@ConditionalOnClass(name = {"io.netty.channel.Channel", "io.grpc.netty.NettyServerBuilder"})
@Bean
public NettyGrpcServerFactory nettyGrpcServerFactory(final GrpcServerProperties properties,
        final GrpcServiceDiscoverer serviceDiscoverer, final List<GrpcServerConfigurer> serverConfigurers) {
    final NettyGrpcServerFactory factory = new NettyGrpcServerFactory(properties, serverConfigurers);
    for (final GrpcServiceDefinition service : serviceDiscoverer.findGrpcServices()) {
        factory.addService(service);
    }
    return factory;
}
 
Example 9
@Lazy
@Bean(name = "dns-service-discovery")
@ConditionalOnClass(CamelContext.class)
public ServiceDiscovery configureServiceDiscoveryFactory() throws Exception {
    DnsServiceDiscoveryFactory factory = new DnsServiceDiscoveryFactory();

    IntrospectionSupport.setProperties(
        camelContext,
        camelContext.getTypeConverter(),
        factory,
        IntrospectionSupport.getNonNullProperties(configuration));

    return factory.newInstance(camelContext);
}
 
Example 10
@Bean(name = HystrixConstants.DEFAULT_HYSTRIX_CONFIGURATION_ID)
@ConditionalOnClass(CamelContext.class)
@ConditionalOnMissingBean(name = HystrixConstants.DEFAULT_HYSTRIX_CONFIGURATION_ID)
public HystrixConfigurationDefinition defaultHystrixConfigurationDefinition() throws Exception {
    Map<String, Object> properties = new HashMap<>();

    IntrospectionSupport.getProperties(config, properties, null, false);
    HystrixConfigurationDefinition definition = new HystrixConfigurationDefinition();
    IntrospectionSupport.setProperties(camelContext, camelContext.getTypeConverter(), definition, properties);

    return definition;
}
 
Example 11
@Bean(name = ResilienceConstants.DEFAULT_RESILIENCE_CONFIGURATION_ID)
@ConditionalOnClass(CamelContext.class)
@ConditionalOnMissingBean(name = ResilienceConstants.DEFAULT_RESILIENCE_CONFIGURATION_ID)
public Resilience4jConfigurationDefinition defaultResilienceConfigurationDefinition() throws Exception {
    Map<String, Object> properties = new HashMap<>();

    IntrospectionSupport.getProperties(config, properties, null, false);
    Resilience4jConfigurationDefinition definition = new Resilience4jConfigurationDefinition();
    IntrospectionSupport.setProperties(camelContext, camelContext.getTypeConverter(), definition, properties);

    return definition;
}
 
Example 12
@Lazy
@Bean(name = "ribbon-load-balancer")
@ConditionalOnClass(CamelContext.class)
public ServiceLoadBalancer configureLoadBalancerFactory() throws Exception {
    RibbonServiceLoadBalancerFactory factory = new RibbonServiceLoadBalancerFactory();

    IntrospectionSupport.setProperties(
        camelContext,
        camelContext.getTypeConverter(),
        factory,
        IntrospectionSupport.getNonNullProperties(configuration));

    return factory.newInstance(camelContext);
}
 
Example 13
@ConditionalOnProperty(name = BASE_PACKAGES_PROPERTY_NAME)
@ConditionalOnClass(ConfigurationPropertySources.class)
@Bean
public FeignClientToDubboProviderBeanPostProcessor feignClientToDubboProviderBeanPostProcessor(Environment environment) {
    Set<String> packagesToScan = environment.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet());
    return new FeignClientToDubboProviderBeanPostProcessor(packagesToScan);
}
 
Example 14
Source Project: open-cloud   Source File: GatewayConfiguration.java    License: MIT License 5 votes vote down vote up
/**
 * 自定义网关监控端点
 *
 * @param context
 * @param bus
 * @return
 */
@Bean
@ConditionalOnEnabledEndpoint
@ConditionalOnClass({Endpoint.class})
public ApiEndpoint apiEndpoint(ApplicationContext context, BusProperties bus) {
    ApiEndpoint endpoint = new ApiEndpoint(context, bus.getId());
    log.info("ApiEndpoint [{}]", endpoint);
    return endpoint;
}
 
Example 15
Source Project: open-cloud   Source File: ApiConfiguration.java    License: MIT License 5 votes vote down vote up
/**
 * 网关bus端点
 *
 * @param context
 * @param bus
 * @return
 */
@Bean
@ConditionalOnEnabledEndpoint
@ConditionalOnClass({Endpoint.class})
public ApiEndpoint apiEndpoint(ApplicationContext context, BusProperties bus) {
    ApiEndpoint endpoint = new ApiEndpoint(context, bus.getId());
    log.info("ApiEndpoint [{}]", endpoint);
    return endpoint;
}
 
Example 16
Source Project: open-cloud   Source File: SmsConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
@ConditionalOnClass({ AliyunSmsSenderImpl.class })
public SmsSender smsSender(AliyunSmsProperties aliyunSmsProperties) {
       AliyunSmsSenderImpl sender = new AliyunSmsSenderImpl();
	BeanUtils.copyProperties(aliyunSmsProperties, sender);
	return sender;
}
 
Example 17
Source Project: springdoc-openapi   Source File: SpringDocConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Springdoc bean factory post processor bean factory post processor.
 *
 * @return the bean factory post processor
 */
@Bean
@Conditional(CacheOrGroupedOpenApiCondition.class)
@ConditionalOnClass(name = BINDRESULT_CLASS)
@Lazy(false)
static BeanFactoryPostProcessor springdocBeanFactoryPostProcessor() {
	return new SpringdocBeanFactoryConfigurer();
}
 
Example 18
Source Project: cola   Source File: AliyunSmsSenderConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
@ConditionalOnClass({AliyunSmsSender.class})
@ConditionalOnProperty(name = "spring.notify.sms.aliyun.accessKeyId")
public SmsSender smsSender() {
	AliyunSmsSender sender = new AliyunSmsSender();
	BeanUtils.copyProperties(aliyunSmsProperties, sender);
	return sender;
}
 
Example 19
@Bean
@RxMVC
@ConditionalOnMissingBean
@ConditionalOnClass(Observable.class)
public ObservableReturnValueHandler observableReturnValueHandler() {
    return new ObservableReturnValueHandler();
}
 
Example 20
@Bean
@RxMVC
@ConditionalOnMissingBean
@ConditionalOnClass(Single.class)
public SingleReturnValueHandler singleReturnValueHandler() {
    return new SingleReturnValueHandler();
}
 
Example 21
/**
 * Build hibernate transaction manager.
 *
 * @param transactionManagerCustomizers transaction manager customizers
 * @return jpa transaction manager
 */
@Bean
@ConditionalOnMissingBean(PlatformTransactionManager.class)
@ConditionalOnClass(value = LocalContainerEntityManagerFactoryBean.class, name = "javax.persistence.EntityManager")
public PlatformTransactionManager jpaTransactionManager(final ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
    JpaTransactionManager result = new JpaTransactionManager();
    if (null != transactionManagerCustomizers.getIfAvailable()) {
        transactionManagerCustomizers.getIfAvailable().customize(result);
    }
    return result;
}
 
Example 22
@ConditionalOnMissingBean(GrpcChannelFactory.class)
@ConditionalOnClass(name = {"io.grpc.netty.shaded.io.netty.channel.Channel",
        "io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder"})
@Bean
@Lazy
GrpcChannelFactory shadedNettyGrpcChannelFactory(final GrpcChannelsProperties properties,
        final GlobalClientInterceptorRegistry globalClientInterceptorRegistry,
        final List<GrpcChannelConfigurer> channelConfigurers) {
    final ShadedNettyChannelFactory channelFactory =
            new ShadedNettyChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers);
    final InProcessChannelFactory inProcessChannelFactory =
            new InProcessChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers);
    return new InProcessOrAlternativeChannelFactory(properties, inProcessChannelFactory, channelFactory);
}
 
Example 23
@Bean
@ConditionalOnProperty(prefix = "quickfixj.client", name = "jmx-enabled", havingValue = "true")
@ConditionalOnClass(JmxExporter.class)
@ConditionalOnSingleCandidate(Initiator.class)
@ConditionalOnMissingBean(name = "clientInitiatorMBean", value = ObjectName.class)
public ObjectName clientInitiatorMBean(Initiator clientInitiator) {
	try {
		JmxExporter exporter = new JmxExporter();
		exporter.setRegistrationBehavior(REGISTRATION_REPLACE_EXISTING);
		return exporter.register(clientInitiator);
	} catch (Exception e) {
		throw new ConfigurationException(e.getMessage(), e);
	}
}
 
Example 24
/**
 * JSON 格式 {@link Formatter} Bean
 *
 * @return {@link JsonFormatter}
 */
@Bean
@ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
@ConditionalOnMissingBean(type = "com.fasterxml.jackson.databind.ObjectMapper")
public Formatter jsonFormatter() {
    return new JsonFormatter();
}
 
Example 25
/**
 * Create a {@code ReactiveClientRegistrationRepository} bean for use with an
 * OAuth2-enabled {@code ReactiveCredHubTemplate}, in case
 * {@link ReactiveOAuth2ClientAutoConfiguration} doesn't configure one.
 * @return the {@code ReactiveClientRegistrationRepository}
 */
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient")
public ReactiveClientRegistrationRepository credHubReactiveClientRegistrationRepository() {
	List<ClientRegistration> registrations = new ArrayList<>(
			OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(this.properties).values());
	return new InMemoryReactiveClientRegistrationRepository(registrations);
}
 
Example 26
@Bean
@Scope("prototype")
@ConditionalOnClass(name = { "com.netflix.hystrix.HystrixCommand", "feign.hystrix.HystrixFeign" })
@ConditionalOnProperty(name = "feign.hystrix.enabled", havingValue = "true")
Feign.Builder feignHystrixBuilder() {
    return SofaTracerHystrixFeignBuilder.builder();
}
 
Example 27
@ConditionalOnMissingBean(GrpcChannelFactory.class)
@ConditionalOnClass(name = {"io.netty.channel.Channel", "io.grpc.netty.NettyChannelBuilder"})
@Bean
@Lazy
GrpcChannelFactory nettyGrpcChannelFactory(final GrpcChannelsProperties properties,
        final GlobalClientInterceptorRegistry globalClientInterceptorRegistry,
        final List<GrpcChannelConfigurer> channelConfigurers) {
    final NettyChannelFactory channelFactory =
            new NettyChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers);
    final InProcessChannelFactory inProcessChannelFactory =
            new InProcessChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers);
    return new InProcessOrAlternativeChannelFactory(properties, inProcessChannelFactory, channelFactory);
}
 
Example 28
/**
 * Creates a GrpcServerFactory using the shaded netty. This is the recommended default for gRPC.
 *
 * @param properties The properties used to configure the server.
 * @param serviceDiscoverer The discoverer used to identify the services that should be served.
 * @param serverConfigurers The server configurers that contain additional configuration for the server.
 * @return The shadedNettyGrpcServerFactory bean.
 */
@ConditionalOnClass(name = {"io.grpc.netty.shaded.io.netty.channel.Channel",
        "io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder"})
@Conditional(ConditionalOnInterprocessServer.class)
@Bean
public ShadedNettyGrpcServerFactory shadedNettyGrpcServerFactory(final GrpcServerProperties properties,
        final GrpcServiceDiscoverer serviceDiscoverer, final List<GrpcServerConfigurer> serverConfigurers) {
    final ShadedNettyGrpcServerFactory factory = new ShadedNettyGrpcServerFactory(properties, serverConfigurers);
    for (final GrpcServiceDefinition service : serviceDiscoverer.findGrpcServices()) {
        factory.addService(service);
    }
    return factory;
}
 
Example 29
@ConditionalOnProperty(name = BASE_PACKAGES_PROPERTY_NAME)
@ConditionalOnClass(ConfigurationPropertySources.class)
@Bean
public FeignClientToDubboProviderBeanPostProcessor feignClientToDubboProviderBeanPostProcessor(Environment environment) {
    Set<String> packagesToScan = environment.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet());
    return new FeignClientToDubboProviderBeanPostProcessor(packagesToScan);
}
 
Example 30
/**
 * It is used to register the tomcat valve with the tomcat container.
 * 
 * @return embeddedTomcat
 */
@Bean
@ConditionalOnClass({ Servlet.class, Tomcat.class })
public ServletWebServerFactory servletContainerWithSemaphoreRateLimiterValve() {
	TomcatServletWebServerFactory embeddedTomcat = new TomcatServletWebServerFactory();
	embeddedTomcat.addEngineValves(new ProductShedLoadSemaphoreValve(shedLoad));
	return embeddedTomcat;
}