org.springframework.boot.autoconfigure.condition.ConditionalOnProperty Java Examples

The following examples show how to use org.springframework.boot.autoconfigure.condition.ConditionalOnProperty. 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: CloudConfig.java    From cf-butler with Apache License 2.0 8 votes vote down vote up
@Bean
@ConditionalOnProperty(VCAP_SERVICE_VARIABLE)
ConnectionFactory connectionFactory() {
    R2dbcProperties properties = r2dbcProperties();
    ConnectionFactoryOptions.Builder builder = ConnectionFactoryOptions
            .parse(properties.getUrl()).mutate();
    String username = properties.getUsername();
    if (StringUtils.hasText(username)) {
        builder.option(ConnectionFactoryOptions.USER, username);
    }
    String password = properties.getPassword();
    if (StringUtils.hasText(password)) {
        builder.option(ConnectionFactoryOptions.PASSWORD, password);
    }
    String databaseName = properties.getName();
    if (StringUtils.hasText(databaseName)) {
        builder.option(ConnectionFactoryOptions.DATABASE, databaseName);
    }
    if (properties.getProperties() != null) {
        properties.getProperties()
                .forEach((key, value) -> builder
                        .option(Option.valueOf(key), value));
    }
    return ConnectionFactories.get(builder.build());
}
 
Example #2
Source File: ImportDataConfiguration.java    From sbp with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "spring.flyway", name = "import-data")
@DependsOn("flywayInitializer")
public FlywayDataImporter flywayDataImporter() {
    FluentConfiguration flywayConf = plugin != null
            ? Flyway.configure(plugin.getWrapper().getPluginClassLoader()) : Flyway.configure();
    flywayConf.configuration(flyway.getConfiguration());
    flywayConf.baselineVersion("0");
    flywayConf.baselineOnMigrate(true);
    flywayConf.locations("classpath:/db_data");
    flywayConf.table("_db_data");
    Flyway importDataFlyway = new Flyway(flywayConf);
    FlywayDataImporter importer = new FlywayDataImporter(importDataFlyway);
    importer.setOrder(Ordered.LOWEST_PRECEDENCE);
    return importer;
}
 
Example #3
Source File: AtomixClusterServiceAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
@Bean(name = "atomix-cluster-service")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@ConditionalOnProperty(prefix = "camel.component.atomix.cluster.service", name = "mode", havingValue = "node")
public CamelClusterService atomixClusterService() {
    AtomixClusterService service = new AtomixClusterService();
    service.setNodes(configuration.getNodes().stream().map(Address::new).collect(Collectors.toList()));

    ObjectHelper.ifNotEmpty(configuration.isEphemeral(), service::setEphemeral);
    ObjectHelper.ifNotEmpty(configuration.getId(), service::setId);
    ObjectHelper.ifNotEmpty(configuration.getAddress(), service::setAddress);
    ObjectHelper.ifNotEmpty(configuration.getStoragePath(), service::setStoragePath);
    ObjectHelper.ifNotEmpty(configuration.getStorageLevel(), service::setStorageLevel);
    ObjectHelper.ifNotEmpty(configuration.getConfigurationUri(), service::setConfigurationUri);
    ObjectHelper.ifNotEmpty(configuration.getAttributes(), service::setAttributes);
    ObjectHelper.ifNotEmpty(configuration.getOrder(), service::setOrder);

    return service;
}
 
Example #4
Source File: RedisConfig.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Primary
@Bean("redisTemplate")
// 没有此属性就不会装配bean 如果是单个redis 将此注解注释掉
@ConditionalOnProperty(name = "spring.redis.cluster.nodes", matchIfMissing = false)
public RedisTemplate<String, Object> getRedisTemplate() {
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
	redisTemplate.setConnectionFactory(lettuceConnectionFactory);

	RedisSerializer stringSerializer = new StringRedisSerializer();
	// RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
	RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
	redisTemplate.setKeySerializer(stringSerializer); // key的序列化类型
	redisTemplate.setHashKeySerializer(stringSerializer);
	redisTemplate.setValueSerializer(redisObjectSerializer); // value的序列化类型
	redisTemplate.setHashValueSerializer(redisObjectSerializer); // value的序列化类型
	redisTemplate.afterPropertiesSet();

	redisTemplate.opsForValue().set("hello", "wolrd");
	return redisTemplate;
}
 
Example #5
Source File: RSocketBrokerAutoConfiguration.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Bean
@Order(101)
@ConditionalOnProperty(name = "rsocket.broker.ssl.key-store")
RSocketListenerCustomizer rSocketListenerSSLCustomizer(@Autowired RSocketBrokerProperties properties,
                                                       @Autowired ResourceLoader resourceLoader) {
    return builder -> {
        RSocketBrokerProperties.RSocketSSL rSocketSSL = properties.getSsl();
        if (rSocketSSL != null && rSocketSSL.isEnabled() && rSocketSSL.getKeyStore() != null) {
            try {
                KeyStore store = KeyStore.getInstance("PKCS12");
                store.load(resourceLoader.getResource(rSocketSSL.getKeyStore()).getInputStream(), rSocketSSL.getKeyStorePassword().toCharArray());
                String alias = store.aliases().nextElement();
                Certificate certificate = store.getCertificate(alias);
                KeyStore.Entry entry = store.getEntry(alias, new KeyStore.PasswordProtection(rSocketSSL.getKeyStorePassword().toCharArray()));
                PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
                builder.sslContext(certificate, privateKey);
                builder.listen("tcps", properties.getPort());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #6
Source File: MirrorImporterConfiguration.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "hedera.mirror.importer.downloader", name = "cloudProvider", havingValue = "GCP")
public S3AsyncClient gcpCloudStorageClient() {
    log.info("Configured to download from GCP with bucket name '{}'", downloaderProperties.getBucketName());
    // Any valid region for aws client. Ignored by GCP.
    S3AsyncClientBuilder clientBuilder = asyncClientBuilder("us-east-1")
            .endpointOverride(URI.create(downloaderProperties.getCloudProvider().getEndpoint()));
    String projectId = downloaderProperties.getGcpProjectId();
    if (StringUtils.isNotBlank(projectId)) {
        clientBuilder.overrideConfiguration(builder -> builder.addExecutionInterceptor(new ExecutionInterceptor() {
            @Override
            public SdkHttpRequest modifyHttpRequest(
                    Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
                return context.httpRequest().toBuilder()
                        .appendRawQueryParameter("userProject", projectId).build();
            }
        }));
    }
    return clientBuilder.build();
}
 
Example #7
Source File: DruidConfig.java    From supplierShop with MIT License 5 votes vote down vote up
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties)
{
    DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
    return druidProperties.dataSource(dataSource);
}
 
Example #8
Source File: DruidConfig.java    From supplierShop with MIT License 5 votes vote down vote up
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties)
{
    DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
    return druidProperties.dataSource(dataSource);
}
 
Example #9
Source File: AliyunSmsSenderConfiguration.java    From cola with 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 #10
Source File: ServiceCombConfigAutoConfiguration.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.cloud.servicecomb.config.watch.enabled",
    matchIfMissing = true)
public ConfigWatch configWatch(ServiceCombConfigProperties serviceCombConfigProperties,
    ServiceCombConfigClient serviceCombConfigClient,
    ContextRefresher contextRefresher, RefreshRecord refreshRecord,
    ServiceCombAkSkProperties serviceCombAkSkProperties) {
  ConfigWatch watch = new ConfigWatch();
  watch.setProject(serviceCombAkSkProperties.getProject());
  watch.setContextRefresher(contextRefresher);
  watch.setServiceCombConfigClient(serviceCombConfigClient);
  watch.setServiceCombConfigProperties(serviceCombConfigProperties);
  watch.setRefreshRecord(refreshRecord);
  return watch;
}
 
Example #11
Source File: ServiceCombDiscoveryClientConfiguration.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(value = "spring.cloud.servicecomb.discovery.enabled", matchIfMissing = true)
public ServiceCombClient serviceCombClient(ServiceCombDiscoveryProperties serviceCombProperties,
    ServiceCombAkSkProperties serviceCombAkSkProperties, ServiceCombSSLProperties serviceCombSSLProperties) {
  ServiceCombClientBuilder builder = new ServiceCombClientBuilder();
  if (!StringUtils.isEmpty(serviceCombAkSkProperties.getEnable())) {
    throw new ServiceCombRuntimeException(
        "config credentials.enable has change to credentials.enabled ,old names are no longer supported, please change it.");
  }
  builder
      .setUrl(serviceCombProperties.getAddress())
      .setServiceCombAkSkProperties(serviceCombAkSkProperties)
      .setServiceCombSSLProperties(serviceCombSSLProperties);
  return builder.createServiceCombClient();
}
 
Example #12
Source File: CasbinAutoConfiguration.java    From casbin-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 自动配置文件存储适配器
 */
@Bean
@ConditionalOnProperty(name = "casbin.storeType", havingValue = "file")
@ConditionalOnMissingBean
public Adapter autoConfigFileAdapter(CasbinProperties properties) {
    // 选择使用文件存储并正确设置了policy文件位置,则创建文件适配器
    if (!StringUtils.isEmpty(properties.getPolicy())) {
        try (InputStream policyInputStream = properties.getPolicyInputStream()) {
            return new FileAdapter(policyInputStream);
        } catch (Exception ignored) {
        }
    }
    throw new CasbinAdapterException("Cannot create file adapter, because policy file is not set");
}
 
Example #13
Source File: MetricsConfiguration.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty("jhipster.logging.spectator-metrics.enabled")
@ExportMetricReader
public SpectatorMetricReader spectatorMetricReader(Registry registry) {
    log.info("Initializing Spectator Metrics Log reporting");
    return new SpectatorMetricReader(registry);
}
 
Example #14
Source File: Neo4jReactiveDataConfiguration.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Bean("reactiveDatabaseSelectionProvider")
@ConditionalOnProperty(prefix = "org.neo4j.data", name = "database")
@ConditionalOnMissingBean
@Order(-30)
public ReactiveDatabaseSelectionProvider staticDatabaseSelectionProvider(Neo4jDataProperties dataProperties) {

	return ReactiveDatabaseSelectionProvider.createStaticDatabaseSelectionProvider(dataProperties.getDatabase());
}
 
Example #15
Source File: MetricsConfiguration.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty("jhipster.logging.spectator-metrics.enabled")
@ExportMetricReader
public SpectatorMetricReader spectatorMetricReader(Registry registry) {
    log.info("Initializing Spectator Metrics Log reporting");
    return new SpectatorMetricReader(registry);
}
 
Example #16
Source File: ProxyConfiguration.java    From cymbal with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "proxy.prometheus.enable", havingValue = "true")
public ServletRegistrationBean prometheusProxyServletRegistration() {
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(new URITemplateProxyServlet(),
            "/prometheus/*");
    registrationBean.setName("prometheus");
    registrationBean.setInitParameters(proxyProperties.getPrometheus());
    return registrationBean;
}
 
Example #17
Source File: RedisAtomConfig.java    From Milkomeda with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(prefix = "milkomeda.atom.redis", name = "use-cluster", havingValue = "true")
public RedissonClient clusterRedissonClient() {
    Config config = new Config();
    ClusterServersConfig clusterServersConfig = config.useClusterServers();
    for (String node : redisProperties.getCluster().getNodes()) {
        clusterServersConfig.addNodeAddress(String.format("redis://%s", node));
    }
    clusterServersConfig.setPassword(redisProperties.getPassword());
    if (redisProperties.getTimeout() != null) {
        clusterServersConfig.setTimeout((int) redisProperties.getTimeout().toMillis());
    }
    return Redisson.create(config);
}
 
Example #18
Source File: SpringDocConfiguration.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Schema property deprecating converter schema property deprecating converter.
 *
 * @return the schema property deprecating converter
 */
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = SPRINGDOC_DEPRECATING_CONVERTER_ENABLED, matchIfMissing = true)
@Lazy(false)
SchemaPropertyDeprecatingConverter schemaPropertyDeprecatingConverter() {
	return new SchemaPropertyDeprecatingConverter();
}
 
Example #19
Source File: MetricsConfiguration.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty("jhipster.logging.spectator-metrics.enabled")
@ExportMetricReader
public SpectatorMetricReader spectatorMetricReader(Registry registry) {
    log.info("Initializing Spectator Metrics Log reporting");
    return new SpectatorMetricReader(registry);
}
 
Example #20
Source File: LraServiceAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean(name = "lra-service")
@ConditionalOnMissingBean(CamelSagaService.class)
@ConditionalOnProperty(value = "camel.service.lra.enabled", havingValue = "true")
public LRASagaService configureLraSagaService(LraServiceConfiguration configuration) throws Exception {
    LRASagaService service = new LRASagaService();

    service.setCoordinatorUrl(configuration.getCoordinatorUrl());
    service.setCoordinatorContextPath(configuration.getCoordinatorContextPath());
    service.setLocalParticipantUrl(configuration.getLocalParticipantUrl());
    service.setLocalParticipantContextPath(configuration.getLocalParticipantContextPath());

    camelContext.addService(service);
    return service;
}
 
Example #21
Source File: DynamicDataSourceConfiguration.java    From open-cloud with MIT License 5 votes vote down vote up
@ConditionalOnProperty(value = "opencloud.tenant",matchIfMissing = true)
@ConditionalOnMissingBean(DynamicDataSourceAspect.class)
@Bean
public DynamicDataSourceAspect dynamicDataSourceAspect(OpenTenantProperties openSaasProperties){
    logger.info("==> Current tenant is [{}]",openSaasProperties.getTenantId());
   return new DynamicDataSourceAspect(openSaasProperties);
}
 
Example #22
Source File: GatewayRSocketClientAutoConfiguration.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.cloud.gateway.rsocket.client.auto-connect",
		matchIfMissing = true)
public BrokerClientConnectionListener brokerClientConnectionListener(
		BrokerClient client, ApplicationEventPublisher publisher) {
	return new BrokerClientConnectionListener(client, publisher);
}
 
Example #23
Source File: GatewayRSocketAutoConfiguration.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(value = "spring.cloud.gateway.rsocket.broker.actuator.enabled",
		matchIfMissing = true)
public BrokerActuator brokerActuator(BrokerProperties properties,
		ClusterService clusterService, RoutingTable routingTable) {
	return new BrokerActuator(properties, clusterService, routingTable);
}
 
Example #24
Source File: TokenStoreConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Bean
	@ConditionalOnProperty(prefix="security.oauth2.token.store",name="type" ,havingValue="jdbc" ,matchIfMissing=false)
	public JdbcTokenStore jdbcTokenStore(){
 
//		oauth_access_token oauth_refresh_token 创建两张表
//		return new JdbcTokenStore( dataSource ) ;
		return new JdbcTokenStore( dataSource ) ;

	}
 
Example #25
Source File: SpringDocConfiguration.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Properties resolver for schema open api customiser.
 *
 * @param propertyResolverUtils the property resolver utils
 * @param openAPIBuilder the open api builder
 * @return the open api customiser
 */
@Bean
@ConditionalOnProperty(SPRINGDOC_SCHEMA_RESOLVE_PROPERTIES)
@Lazy(false)
OpenApiCustomiser propertiesResolverForSchema(PropertyResolverUtils propertyResolverUtils, OpenAPIBuilder openAPIBuilder) {
	return openApi -> {
		Components components = openApi.getComponents();
		Map<String, Schema> schemas = components.getSchemas();
		schemas.values().forEach(schema -> openAPIBuilder.resolveProperties(schema, propertyResolverUtils));
	};
}
 
Example #26
Source File: AppPublisherConfiguration.java    From sofa-dashboard-client with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = SofaDashboardClientProperties.SOFA_DASHBOARD_PREFIX, value = "arkEnable", matchIfMissing = true)
public ArkBizLifecycleHandler bizStateListener(IntrospectBizEndpoint endpoint,
                                               Application application) {
    return new ArkBizLifecycleHandler(endpoint, application);
}
 
Example #27
Source File: TokenStoreConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Bean
	@ConditionalOnProperty(prefix="security.oauth2.token.store",name="type" ,havingValue="jdbc" ,matchIfMissing=false)
	public JdbcTokenStore jdbcTokenStore(){
 
//		oauth_access_token oauth_refresh_token 创建两张表
//		return new JdbcTokenStore( dataSource ) ;
		return new JdbcTokenStore( dataSource ) ;

	}
 
Example #28
Source File: TokenStoreConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Bean
	@ConditionalOnProperty(prefix="security.oauth2.token.store",name="type" ,havingValue="redis" ,matchIfMissing=true)
	public RedisTemplateTokenStore redisTokenStore(){
//		return new RedisTokenStore( redisTemplate.getConnectionFactory() ) ; //单台redis服务器
		Assert.state(redisTemplate != null, "RedisTemplate must be provided");

		RedisTemplateTokenStore redisTemplateStore = new RedisTemplateTokenStore()  ;
		redisTemplateStore.setRedisTemplate(redisTemplate);
		return redisTemplateStore ;
		 

	}
 
Example #29
Source File: ApiBootLoggingGlobalLogStorageAutoConfiguration.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Instance global log memory mode storage
 *
 * @return {@link GlobalLoggingMemoryStorage}
 */
@Bean
@ConditionalOnProperty(prefix = API_BOOT_LOGGING_PREFIX,
    name = "global-logging-storage-away", havingValue = "memory", matchIfMissing = true)
public GlobalLogging globalLogging() {
    return new GlobalLoggingMemoryStorage();
}
 
Example #30
Source File: AuthorityMybatisAutoConfiguration.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 数据权限插件
 *
 * @return DataScopeInterceptor
 */
@Order(10)
@Bean
@ConditionalOnProperty(prefix = DatabaseProperties.PREFIX, name = "isDataScope", havingValue = "true", matchIfMissing = true)
public DataScopeInterceptor dataScopeInterceptor() {
    return new DataScopeInterceptor((userId) -> SpringUtils.getBean(UserService.class).getDataScopeById(userId));
}