下面列出了怎么用org.springframework.boot.autoconfigure.condition.ConditionalOnExpression的API类实例代码及写法,或者点击链接到github查看源代码。
@Bean
@ConditionalOnExpression("${in.clouthink.daas.sbb.support.cors.enabled:true}")
@Autowired
public FilterRegistrationBean filterRegistrationBean(CorsSupportProperties corsSupportProperties) {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(corsSupportProperties.isAllowCredentials());
corsConfiguration.addAllowedOrigin(corsSupportProperties.getAllowOrigin());
corsConfiguration.addAllowedHeader(corsSupportProperties.getAllowHeader());
corsConfiguration.addAllowedMethod(corsSupportProperties.getAllowMethod());
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
CorsFilter corsFilter = new CorsFilter(urlBasedCorsConfigurationSource);
FilterRegistrationBean registration = new FilterRegistrationBean(corsFilter);
registration.addUrlPatterns("/*");
registration.setOrder(corsSupportProperties.getOrder());
return registration;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource() {
log.debug("Configuring Datasource");
if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) {
log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariConfig config = new HikariConfig();
config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
if (StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
} else {
config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
}
config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));
if (metricRegistry != null) {
config.setMetricRegistry(metricRegistry);
}
return new HikariDataSource(config);
}
@ConditionalOnExpression("!(" + REMOTE_API_ENABLED_CONDITION + ")")
@Bean
public Docket defaultDocket()
{
ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).select();
builder.paths(path -> false);
return builder.build()
.groupName("Remote API disbled")
.apiInfo(new ApiInfoBuilder()
.title("Remote API disabled")
.description(String.join(" ",
"The remote API is disabled."))
.license("")
.licenseUrl("")
.build());
}
@ConditionalOnExpression(REMOTE_API_ENABLED_CONDITION)
@Bean
public Docket areoRemoteApiDocket()
{
ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).select();
builder.paths(path -> path.matches(AeroRemoteApiController.API_BASE + "/.*"));
return builder.build()
.groupName("AERO API")
.apiInfo(new ApiInfoBuilder()
.title("AERO")
.version("1.0.0")
.description(String.join(" ",
"Annotation Editor Remote Operations API. ",
"https://openminted.github.io/releases/aero-spec/1.0.0/omtd-aero/"))
.license("Apache License 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.txt")
.build())
.genericModelSubstitutes(Optional.class);
}
/**
* TCP connection to connect with SQL clients to the embedded h2 database.
* <p>
* Connect to "jdbc:h2:tcp://localhost:9092/mem:testdb", username "sa", password empty.
*/
@Bean
@ConditionalOnExpression("${h2.tcp.enabled:true}")
public Server h2TcpServer() throws SQLException
{
return Server.createTcpServer("-tcp",
"-tcpAllowOthers",
"-tcpPort",
h2TcpPort)
.start();
}
/**
* Web console for the embedded h2 database.
* <p>
* Go to http://localhost:8082 and connect to the database "jdbc:h2:mem:testdb", username "sa", password empty.
*/
@Bean
@ConditionalOnExpression("${h2.web.enabled:true}")
public Server h2WebServer() throws SQLException
{
return Server.createWebServer("-web",
"-webAllowOthers",
"-webPort",
h2WebPort)
.start();
}
@Order(100)
@Bean(name = "support#Bootstrap")
@ConditionalOnExpression("${chronus.executor.enabled:true} || ${chronus.master.enabled:true}")
public BootstrapSupport bootstrapSupport() {
BootstrapSupport bootstrap = new BootstrapSupport();
return bootstrap;
}
@Bean
@ConditionalOnExpression("${health-check.geolocation.enabled} == true and ${geolocation.enabled} == true")
HealthChecker geoLocationChecker(Vertx vertx,
@Value("${health-check.geolocation.refresh-period-ms}") long refreshPeriod,
GeoLocationService geoLocationService,
TimeoutFactory timeoutFactory,
Clock clock) {
return new GeoLocationHealthChecker(vertx, refreshPeriod, geoLocationService, timeoutFactory, clock);
}
/**
* PrimefacesFileUploadServletContextInitializer for native uploader,
* since {@link FileUploadFilter} suffices for commons file uploader.
*
* @param multipartConfigElement {@link MultipartAutoConfiguration#multipartConfigElement()}
* @return primefaces file upload servlet context initializer
*/
@ConditionalOnExpression("'${joinfaces.primefaces.uploader}' != 'commons'")
@Bean
public ServletContextInitializer primefacesFileUploadServletContextInitializer(MultipartConfigElement multipartConfigElement) {
return servletContext -> {
ServletRegistration servletRegistration = servletContext.getServletRegistration(FACES_SERVLET_NAME);
if (servletRegistration instanceof ServletRegistration.Dynamic) {
((ServletRegistration.Dynamic) servletRegistration).setMultipartConfig(multipartConfigElement);
}
};
}
@Bean
@ConditionalOnExpression("${fiat.write-mode.enabled:true}")
String addUnrestrictedUser(PermissionsRepository permissionsRepository) {
if (!permissionsRepository.get(UNRESTRICTED_USERNAME).isPresent()) {
permissionsRepository.put(new UserPermission().setId(UNRESTRICTED_USERNAME));
}
return UNRESTRICTED_USERNAME;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties<% if (hibernateCache == 'hazelcast') { %>, CacheManager cacheManager<% } %>) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
<%_ if (devDatabaseType == 'h2Disk' || devDatabaseType == 'h2Memory') { _%>
@Bean(destroyMethod = "shutdown")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource() {
log.debug("Configuring Datasource");
if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariConfig config = new HikariConfig();
config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
if(StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
} else {
config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
}
config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));
if (metricRegistry != null) {
config.setMetricRegistry(metricRegistry);
}
return new HikariDataSource(config);
}
@ConditionalOnExpression(REMOTE_API_ENABLED_CONDITION)
@Bean
public Docket legacyRemoteApiDocket()
{
ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).select();
builder.paths(path -> path.matches(LegacyRemoteApiController.API_BASE + "/.*"));
return builder.build()
.groupName("Legacy API")
.genericModelSubstitutes(Optional.class);
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariConfig config = new HikariConfig();
config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
config.addDataSourceProperty("url", dataSourceProperties.getUrl());
if (dataSourceProperties.getUsername() != null) {
config.addDataSourceProperty("user", dataSourceProperties.getUsername());
} else {
config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
}
if (dataSourceProperties.getPassword() != null) {
config.addDataSourceProperty("password", dataSourceProperties.getPassword());
} else {
config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
}
if (metricRegistry != null) {
config.setMetricRegistry(metricRegistry);
}
return new HikariDataSource(config);
}
@ConditionalOnExpression("#{'${keymaster.address}' "
+ "matches '^((\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})|[a-z\\.]+):[0-9]+$'}")
@Bean
public ServiceOps serviceOps() {
return new ZookeeperServiceDiscoveryOps();
//return new ZookeeperServiceOps();
}
@ConditionalOnExpression("#{'${keymaster.address}' matches '^http.+'}")
@Bean
@ConditionalOnMissingBean(name = "selfKeymasterRESTClientFactoryBean")
public JAXRSClientFactoryBean selfKeymasterRESTClientFactoryBean() {
JAXRSClientFactoryBean restClientFactoryBean = new JAXRSClientFactoryBean();
restClientFactoryBean.setAddress(address);
restClientFactoryBean.setUsername(username);
restClientFactoryBean.setPassword(password);
restClientFactoryBean.setThreadSafe(true);
restClientFactoryBean.setInheritHeaders(true);
restClientFactoryBean.setFeatures(List.of(new LoggingFeature()));
restClientFactoryBean.setProviders(
List.of(new JacksonJsonProvider(), new SelfKeymasterClientExceptionMapper()));
return restClientFactoryBean;
}
@Bean
@ConditionalOnExpression("'${rsocket.broker.topology}'=='gossip'")
@Primary
public RSocketBrokerManager rsocketGossipBrokerManager() {
return new RSocketBrokerManagerGossipImpl();
}
@Bean
@ConditionalOnExpression("${zuihou.log.enabled:true} && 'DB'.equals('${zuihou.log.type:LOGGER}')")
public SysLogListener sysLogListener(OptLogService optLogService) {
return new SysLogListener((log) -> optLogService.save(log));
}
@Bean
@ConditionalOnExpression("${h2.tcp.enabled:false}")
public Server h2TcpServer() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2TcpPort).start();
}
@Bean
@ConditionalOnExpression("${h2.web.enabled:false}")
public Server h2WebServer() throws SQLException {
return Server.createWebServer("-web", "-webAllowOthers", "-webPort", h2WebPort).start();
}
@Bean
@ConditionalOnExpression("${zuihou.log.enabled:true} && 'DB'.equals('${zuihou.log.type:LOGGER}')")
public SysLogListener sysLogListener(LogApi logApi) {
return new SysLogListener((log) -> logApi.save(log));
}
@Bean
@ConditionalOnExpression("${zuihou.log.enabled:true} && 'DB'.equals('${zuihou.log.type:LOGGER}')")
public SysLogListener sysLogListener(LogApi logApi) {
return new SysLogListener((log) -> logApi.save(log));
}
@Bean
@ConditionalOnExpression("${paascloud.aliyun.rocketMq.reliableMessageConsumer:true}")
public MqConsumerStoreAspect mqConsumerStoreAspect() {
return new MqConsumerStoreAspect();
}
@Bean
@ConditionalOnExpression("${paascloud.aliyun.rocketMq.reliableMessageProducer:true}")
public MqProducerStoreAspect mqProducerStoreAspect() {
return new MqProducerStoreAspect();
}
/**
* Redis cluster cache redis cluster cache.
*
* @return the redis cluster cache
*/
@Bean
@ConditionalOnExpression("'${dew.cluster.cache}'=='redis'")
public RedisClusterCacheWrap redisClusterCache() {
return new RedisClusterCacheWrap(REDIS_TEMPLATES);
}