下面列出了怎么用org.springframework.boot.autoconfigure.condition.ConditionalOnProperty的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
@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;
}
@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());
}
@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;
}
@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);
}
}
};
}
@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();
}
@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);
}
@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);
}
@Bean
@ConditionalOnClass({AliyunSmsSender.class})
@ConditionalOnProperty(name = "spring.notify.sms.aliyun.accessKeyId")
public SmsSender smsSender() {
AliyunSmsSender sender = new AliyunSmsSender();
BeanUtils.copyProperties(aliyunSmsProperties, sender);
return sender;
}
@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;
}
@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();
}
/**
* 自动配置文件存储适配器
*/
@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");
}
@Bean
@ConditionalOnProperty("jhipster.logging.spectator-metrics.enabled")
@ExportMetricReader
public SpectatorMetricReader spectatorMetricReader(Registry registry) {
log.info("Initializing Spectator Metrics Log reporting");
return new SpectatorMetricReader(registry);
}
@Bean("reactiveDatabaseSelectionProvider")
@ConditionalOnProperty(prefix = "org.neo4j.data", name = "database")
@ConditionalOnMissingBean
@Order(-30)
public ReactiveDatabaseSelectionProvider staticDatabaseSelectionProvider(Neo4jDataProperties dataProperties) {
return ReactiveDatabaseSelectionProvider.createStaticDatabaseSelectionProvider(dataProperties.getDatabase());
}
@Bean
@ConditionalOnProperty("jhipster.logging.spectator-metrics.enabled")
@ExportMetricReader
public SpectatorMetricReader spectatorMetricReader(Registry registry) {
log.info("Initializing Spectator Metrics Log reporting");
return new SpectatorMetricReader(registry);
}
@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;
}
@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);
}
/**
* 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();
}
@Bean
@ConditionalOnProperty("jhipster.logging.spectator-metrics.enabled")
@ExportMetricReader
public SpectatorMetricReader spectatorMetricReader(Registry registry) {
log.info("Initializing Spectator Metrics Log reporting");
return new SpectatorMetricReader(registry);
}
@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;
}
@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);
}
@Bean
@ConditionalOnProperty(name = "spring.cloud.gateway.rsocket.client.auto-connect",
matchIfMissing = true)
public BrokerClientConnectionListener brokerClientConnectionListener(
BrokerClient client, ApplicationEventPublisher publisher) {
return new BrokerClientConnectionListener(client, publisher);
}
@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);
}
@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 ) ;
}
/**
* 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));
};
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = SofaDashboardClientProperties.SOFA_DASHBOARD_PREFIX, value = "arkEnable", matchIfMissing = true)
public ArkBizLifecycleHandler bizStateListener(IntrospectBizEndpoint endpoint,
Application application) {
return new ArkBizLifecycleHandler(endpoint, application);
}
@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 ) ;
}
@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 ;
}
/**
* 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();
}
/**
* 数据权限插件
*
* @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));
}