Inject single-use configuration dependencies into bean methods

Closes gh-15751
This commit is contained in:
Andy Wilkinson 2019-02-19 16:18:31 +00:00
parent 34f28b4cbd
commit de0c065625
106 changed files with 933 additions and 1861 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,17 +49,11 @@ import org.springframework.context.annotation.Configuration;
public class RabbitHealthIndicatorAutoConfiguration extends public class RabbitHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> { CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> {
private final Map<String, RabbitTemplate> rabbitTemplates;
public RabbitHealthIndicatorAutoConfiguration(
Map<String, RabbitTemplate> rabbitTemplates) {
this.rabbitTemplates = rabbitTemplates;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "rabbitHealthIndicator") @ConditionalOnMissingBean(name = "rabbitHealthIndicator")
public HealthIndicator rabbitHealthIndicator() { public HealthIndicator rabbitHealthIndicator(
return createHealthIndicator(this.rabbitTemplates); Map<String, RabbitTemplate> rabbitTemplates) {
return createHealthIndicator(rabbitTemplates);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,17 +42,11 @@ import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
public class AuditAutoConfiguration { public class AuditAutoConfiguration {
private final AuditEventRepository auditEventRepository;
public AuditAutoConfiguration(
ObjectProvider<AuditEventRepository> auditEventRepository) {
this.auditEventRepository = auditEventRepository.getIfAvailable();
}
@Bean @Bean
@ConditionalOnMissingBean(AbstractAuditListener.class) @ConditionalOnMissingBean(AbstractAuditListener.class)
public AuditListener auditListener() throws Exception { public AuditListener auditListener(
return new AuditListener(this.auditEventRepository); ObjectProvider<AuditEventRepository> auditEventRepository) throws Exception {
return new AuditListener(auditEventRepository.getIfAvailable());
} }
@Bean @Bean

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -56,17 +56,11 @@ import org.springframework.data.cassandra.core.CassandraOperations;
public class CassandraHealthIndicatorAutoConfiguration extends public class CassandraHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<CassandraHealthIndicator, CassandraOperations> { CompositeHealthIndicatorConfiguration<CassandraHealthIndicator, CassandraOperations> {
private final Map<String, CassandraOperations> cassandraOperations;
public CassandraHealthIndicatorAutoConfiguration(
Map<String, CassandraOperations> cassandraOperations) {
this.cassandraOperations = cassandraOperations;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "cassandraHealthIndicator") @ConditionalOnMissingBean(name = "cassandraHealthIndicator")
public HealthIndicator cassandraHealthIndicator() { public HealthIndicator cassandraHealthIndicator(
return createHealthIndicator(this.cassandraOperations); Map<String, CassandraOperations> cassandraOperations) {
return createHealthIndicator(cassandraOperations);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,17 +53,11 @@ import org.springframework.data.cassandra.core.ReactiveCassandraOperations;
public class CassandraReactiveHealthIndicatorAutoConfiguration extends public class CassandraReactiveHealthIndicatorAutoConfiguration extends
CompositeReactiveHealthIndicatorConfiguration<CassandraReactiveHealthIndicator, ReactiveCassandraOperations> { CompositeReactiveHealthIndicatorConfiguration<CassandraReactiveHealthIndicator, ReactiveCassandraOperations> {
private final Map<String, ReactiveCassandraOperations> reactiveCassandraOperations;
public CassandraReactiveHealthIndicatorAutoConfiguration(
Map<String, ReactiveCassandraOperations> reactiveCassandraOperations) {
this.reactiveCassandraOperations = reactiveCassandraOperations;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "cassandraReactiveHealthIndicator") @ConditionalOnMissingBean(name = "cassandraReactiveHealthIndicator")
public ReactiveHealthIndicator cassandraHealthIndicator() { public ReactiveHealthIndicator cassandraHealthIndicator(
return createHealthIndicator(this.reactiveCassandraOperations); Map<String, ReactiveCassandraOperations> reactiveCassandraOperations) {
return createHealthIndicator(reactiveCassandraOperations);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -72,12 +72,6 @@ import org.springframework.web.server.WebFilter;
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
public class ReactiveCloudFoundryActuatorAutoConfiguration { public class ReactiveCloudFoundryActuatorAutoConfiguration {
private final ApplicationContext applicationContext;
ReactiveCloudFoundryActuatorAutoConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint @ConditionalOnEnabledEndpoint
@ -92,12 +86,13 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration {
public CloudFoundryWebFluxEndpointHandlerMapping cloudFoundryWebFluxEndpointHandlerMapping( public CloudFoundryWebFluxEndpointHandlerMapping cloudFoundryWebFluxEndpointHandlerMapping(
ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes, ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes,
WebClient.Builder webClientBuilder, WebClient.Builder webClientBuilder,
ControllerEndpointsSupplier controllerEndpointsSupplier) { ControllerEndpointsSupplier controllerEndpointsSupplier,
ApplicationContext applicationContext) {
CloudFoundryWebEndpointDiscoverer endpointDiscoverer = new CloudFoundryWebEndpointDiscoverer( CloudFoundryWebEndpointDiscoverer endpointDiscoverer = new CloudFoundryWebEndpointDiscoverer(
this.applicationContext, parameterMapper, endpointMediaTypes, null, applicationContext, parameterMapper, endpointMediaTypes, null,
Collections.emptyList(), Collections.emptyList()); Collections.emptyList(), Collections.emptyList());
CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor( CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor(
webClientBuilder, this.applicationContext.getEnvironment()); webClientBuilder, applicationContext.getEnvironment());
Collection<ExposableWebEndpoint> webEndpoints = endpointDiscoverer.getEndpoints(); Collection<ExposableWebEndpoint> webEndpoints = endpointDiscoverer.getEndpoints();
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>(); List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
allEndpoints.addAll(webEndpoints); allEndpoints.addAll(webEndpoints);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -76,12 +76,6 @@ import org.springframework.web.servlet.DispatcherServlet;
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
public class CloudFoundryActuatorAutoConfiguration { public class CloudFoundryActuatorAutoConfiguration {
private final ApplicationContext applicationContext;
CloudFoundryActuatorAutoConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint @ConditionalOnEnabledEndpoint
@ -96,12 +90,13 @@ public class CloudFoundryActuatorAutoConfiguration {
ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes, ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes,
RestTemplateBuilder restTemplateBuilder, RestTemplateBuilder restTemplateBuilder,
ServletEndpointsSupplier servletEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier,
ControllerEndpointsSupplier controllerEndpointsSupplier) { ControllerEndpointsSupplier controllerEndpointsSupplier,
ApplicationContext applicationContext) {
CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer( CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer(
this.applicationContext, parameterMapper, endpointMediaTypes, null, applicationContext, parameterMapper, endpointMediaTypes, null,
Collections.emptyList(), Collections.emptyList()); Collections.emptyList(), Collections.emptyList());
CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor( CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor(
restTemplateBuilder, this.applicationContext.getEnvironment()); restTemplateBuilder, applicationContext.getEnvironment());
Collection<ExposableWebEndpoint> webEndpoints = discoverer.getEndpoints(); Collection<ExposableWebEndpoint> webEndpoints = discoverer.getEndpoints();
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>(); List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
allEndpoints.addAll(webEndpoints); allEndpoints.addAll(webEndpoints);

View File

@ -37,18 +37,12 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties(ConfigurationPropertiesReportEndpointProperties.class) @EnableConfigurationProperties(ConfigurationPropertiesReportEndpointProperties.class)
public class ConfigurationPropertiesReportEndpointAutoConfiguration { public class ConfigurationPropertiesReportEndpointAutoConfiguration {
private final ConfigurationPropertiesReportEndpointProperties properties;
public ConfigurationPropertiesReportEndpointAutoConfiguration(
ConfigurationPropertiesReportEndpointProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ConfigurationPropertiesReportEndpoint configurationPropertiesReportEndpoint() { public ConfigurationPropertiesReportEndpoint configurationPropertiesReportEndpoint(
ConfigurationPropertiesReportEndpointProperties properties) {
ConfigurationPropertiesReportEndpoint endpoint = new ConfigurationPropertiesReportEndpoint(); ConfigurationPropertiesReportEndpoint endpoint = new ConfigurationPropertiesReportEndpoint();
String[] keysToSanitize = this.properties.getKeysToSanitize(); String[] keysToSanitize = properties.getKeysToSanitize();
if (keysToSanitize != null) { if (keysToSanitize != null) {
endpoint.setKeysToSanitize(keysToSanitize); endpoint.setKeysToSanitize(keysToSanitize);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,16 +52,10 @@ import org.springframework.context.annotation.Configuration;
public class CouchbaseHealthIndicatorAutoConfiguration public class CouchbaseHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<CouchbaseHealthIndicator, Cluster> { extends CompositeHealthIndicatorConfiguration<CouchbaseHealthIndicator, Cluster> {
private final Map<String, Cluster> clusters;
public CouchbaseHealthIndicatorAutoConfiguration(Map<String, Cluster> clusters) {
this.clusters = clusters;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "couchbaseHealthIndicator") @ConditionalOnMissingBean(name = "couchbaseHealthIndicator")
public HealthIndicator couchbaseHealthIndicator() { public HealthIndicator couchbaseHealthIndicator(Map<String, Cluster> clusters) {
return createHealthIndicator(this.clusters); return createHealthIndicator(clusters);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,17 +52,11 @@ import org.springframework.context.annotation.Configuration;
public class CouchbaseReactiveHealthIndicatorAutoConfiguration extends public class CouchbaseReactiveHealthIndicatorAutoConfiguration extends
CompositeReactiveHealthIndicatorConfiguration<CouchbaseReactiveHealthIndicator, Cluster> { CompositeReactiveHealthIndicatorConfiguration<CouchbaseReactiveHealthIndicator, Cluster> {
private final Map<String, Cluster> clusters;
public CouchbaseReactiveHealthIndicatorAutoConfiguration(
Map<String, Cluster> clusters) {
this.clusters = clusters;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "couchbaseReactiveHealthIndicator") @ConditionalOnMissingBean(name = "couchbaseReactiveHealthIndicator")
public ReactiveHealthIndicator couchbaseReactiveHealthIndicator() { public ReactiveHealthIndicator couchbaseReactiveHealthIndicator(
return createHealthIndicator(this.clusters); Map<String, Cluster> clusters) {
return createHealthIndicator(clusters);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -54,21 +54,17 @@ import org.springframework.context.annotation.Configuration;
public class ElasticSearchClientHealthIndicatorAutoConfiguration extends public class ElasticSearchClientHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<ElasticsearchHealthIndicator, Client> { CompositeHealthIndicatorConfiguration<ElasticsearchHealthIndicator, Client> {
private final Map<String, Client> clients;
private final ElasticsearchHealthIndicatorProperties properties; private final ElasticsearchHealthIndicatorProperties properties;
public ElasticSearchClientHealthIndicatorAutoConfiguration( public ElasticSearchClientHealthIndicatorAutoConfiguration(
Map<String, Client> clients,
ElasticsearchHealthIndicatorProperties properties) { ElasticsearchHealthIndicatorProperties properties) {
this.clients = clients;
this.properties = properties; this.properties = properties;
} }
@Bean @Bean
@ConditionalOnMissingBean(name = "elasticsearchHealthIndicator") @ConditionalOnMissingBean(name = "elasticsearchHealthIndicator")
public HealthIndicator elasticsearchHealthIndicator() { public HealthIndicator elasticsearchHealthIndicator(Map<String, Client> clients) {
return createHealthIndicator(this.clients); return createHealthIndicator(clients);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,17 +53,10 @@ import org.springframework.context.annotation.Configuration;
public class ElasticSearchJestHealthIndicatorAutoConfiguration extends public class ElasticSearchJestHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<ElasticsearchJestHealthIndicator, JestClient> { CompositeHealthIndicatorConfiguration<ElasticsearchJestHealthIndicator, JestClient> {
private final Map<String, JestClient> clients;
public ElasticSearchJestHealthIndicatorAutoConfiguration(
Map<String, JestClient> clients) {
this.clients = clients;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "elasticsearchHealthIndicator") @ConditionalOnMissingBean(name = "elasticsearchHealthIndicator")
public HealthIndicator elasticsearchHealthIndicator() { public HealthIndicator elasticsearchHealthIndicator(Map<String, JestClient> clients) {
return createHealthIndicator(this.clients); return createHealthIndicator(clients);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,17 +53,11 @@ import org.springframework.context.annotation.Configuration;
public class ElasticSearchRestHealthIndicatorAutoConfiguration extends public class ElasticSearchRestHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<ElasticsearchRestHealthIndicator, RestClient> { CompositeHealthIndicatorConfiguration<ElasticsearchRestHealthIndicator, RestClient> {
private final Map<String, RestClient> clients;
public ElasticSearchRestHealthIndicatorAutoConfiguration(
Map<String, RestClient> clients) {
this.clients = clients;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "elasticsearchRestHealthIndicator") @ConditionalOnMissingBean(name = "elasticsearchRestHealthIndicator")
public HealthIndicator elasticsearchRestHealthIndicator() { public HealthIndicator elasticsearchRestHealthIndicator(
return createHealthIndicator(this.clients); Map<String, RestClient> clients) {
return createHealthIndicator(clients);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -29,7 +29,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplicat
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.boot.autoconfigure.web.servlet.JerseyApplicationPath; import org.springframework.boot.autoconfigure.web.servlet.JerseyApplicationPath;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.DispatcherServlet;
@ -58,19 +57,11 @@ public class ServletEndpointManagementContextConfiguration {
@ConditionalOnClass(DispatcherServlet.class) @ConditionalOnClass(DispatcherServlet.class)
public static class WebMvcServletEndpointManagementContextConfiguration { public static class WebMvcServletEndpointManagementContextConfiguration {
private final ApplicationContext context;
public WebMvcServletEndpointManagementContextConfiguration(
ApplicationContext context) {
this.context = context;
}
@Bean @Bean
public ServletEndpointRegistrar servletEndpointRegistrar( public ServletEndpointRegistrar servletEndpointRegistrar(
WebEndpointProperties properties, WebEndpointProperties properties,
ServletEndpointsSupplier servletEndpointsSupplier) { ServletEndpointsSupplier servletEndpointsSupplier,
DispatcherServletPath dispatcherServletPath = this.context DispatcherServletPath dispatcherServletPath) {
.getBean(DispatcherServletPath.class);
return new ServletEndpointRegistrar( return new ServletEndpointRegistrar(
dispatcherServletPath.getRelativePath(properties.getBasePath()), dispatcherServletPath.getRelativePath(properties.getBasePath()),
servletEndpointsSupplier.getEndpoints()); servletEndpointsSupplier.getEndpoints());
@ -83,19 +74,11 @@ public class ServletEndpointManagementContextConfiguration {
@ConditionalOnMissingClass("org.springframework.web.servlet.DispatcherServlet") @ConditionalOnMissingClass("org.springframework.web.servlet.DispatcherServlet")
public static class JerseyServletEndpointManagementContextConfiguration { public static class JerseyServletEndpointManagementContextConfiguration {
private final ApplicationContext context;
public JerseyServletEndpointManagementContextConfiguration(
ApplicationContext context) {
this.context = context;
}
@Bean @Bean
public ServletEndpointRegistrar servletEndpointRegistrar( public ServletEndpointRegistrar servletEndpointRegistrar(
WebEndpointProperties properties, WebEndpointProperties properties,
ServletEndpointsSupplier servletEndpointsSupplier) { ServletEndpointsSupplier servletEndpointsSupplier,
JerseyApplicationPath jerseyApplicationPath = this.context JerseyApplicationPath jerseyApplicationPath) {
.getBean(JerseyApplicationPath.class);
return new ServletEndpointRegistrar( return new ServletEndpointRegistrar(
jerseyApplicationPath.getRelativePath(properties.getBasePath()), jerseyApplicationPath.getRelativePath(properties.getBasePath()),
servletEndpointsSupplier.getEndpoints()); servletEndpointsSupplier.getEndpoints());

View File

@ -39,18 +39,12 @@ import org.springframework.core.env.Environment;
@EnableConfigurationProperties(EnvironmentEndpointProperties.class) @EnableConfigurationProperties(EnvironmentEndpointProperties.class)
public class EnvironmentEndpointAutoConfiguration { public class EnvironmentEndpointAutoConfiguration {
private final EnvironmentEndpointProperties properties;
public EnvironmentEndpointAutoConfiguration(
EnvironmentEndpointProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public EnvironmentEndpoint environmentEndpoint(Environment environment) { public EnvironmentEndpoint environmentEndpoint(Environment environment,
EnvironmentEndpointProperties properties) {
EnvironmentEndpoint endpoint = new EnvironmentEndpoint(environment); EnvironmentEndpoint endpoint = new EnvironmentEndpoint(environment);
String[] keysToSanitize = this.properties.getKeysToSanitize(); String[] keysToSanitize = properties.getKeysToSanitize();
if (keysToSanitize != null) { if (keysToSanitize != null) {
endpoint.setKeysToSanitize(keysToSanitize); endpoint.setKeysToSanitize(keysToSanitize);
} }

View File

@ -26,7 +26,6 @@ import org.springframework.boot.actuate.health.HealthStatusHttpMapper;
import org.springframework.boot.actuate.health.HealthWebEndpointResponseMapper; import org.springframework.boot.actuate.health.HealthWebEndpointResponseMapper;
import org.springframework.boot.actuate.health.OrderedHealthAggregator; import org.springframework.boot.actuate.health.OrderedHealthAggregator;
import org.springframework.boot.actuate.health.ReactiveHealthEndpointWebExtension; import org.springframework.boot.actuate.health.ReactiveHealthEndpointWebExtension;
import org.springframework.boot.actuate.health.ReactiveHealthIndicator;
import org.springframework.boot.actuate.health.ReactiveHealthIndicatorRegistry; import org.springframework.boot.actuate.health.ReactiveHealthIndicatorRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -72,21 +71,17 @@ class HealthEndpointWebExtensionConfiguration {
@ConditionalOnEnabledEndpoint(endpoint = HealthEndpoint.class) @ConditionalOnEnabledEndpoint(endpoint = HealthEndpoint.class)
static class ReactiveWebHealthConfiguration { static class ReactiveWebHealthConfiguration {
private final ReactiveHealthIndicator reactiveHealthIndicator;
ReactiveWebHealthConfiguration(ObjectProvider<HealthAggregator> healthAggregator,
ReactiveHealthIndicatorRegistry registry) {
this.reactiveHealthIndicator = new CompositeReactiveHealthIndicator(
healthAggregator.getIfAvailable(OrderedHealthAggregator::new),
registry);
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnBean(HealthEndpoint.class) @ConditionalOnBean(HealthEndpoint.class)
public ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension( public ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension(
ObjectProvider<HealthAggregator> healthAggregator,
ReactiveHealthIndicatorRegistry registry,
HealthWebEndpointResponseMapper responseMapper) { HealthWebEndpointResponseMapper responseMapper) {
return new ReactiveHealthEndpointWebExtension(this.reactiveHealthIndicator, return new ReactiveHealthEndpointWebExtension(
new CompositeReactiveHealthIndicator(
healthAggregator.getIfAvailable(OrderedHealthAggregator::new),
registry),
responseMapper); responseMapper);
} }

View File

@ -49,12 +49,6 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties({ HealthIndicatorProperties.class }) @EnableConfigurationProperties({ HealthIndicatorProperties.class })
public class HealthIndicatorAutoConfiguration { public class HealthIndicatorAutoConfiguration {
private final HealthIndicatorProperties properties;
public HealthIndicatorAutoConfiguration(HealthIndicatorProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean({ HealthIndicator.class, ReactiveHealthIndicator.class }) @ConditionalOnMissingBean({ HealthIndicator.class, ReactiveHealthIndicator.class })
public ApplicationHealthIndicator applicationHealthIndicator() { public ApplicationHealthIndicator applicationHealthIndicator() {
@ -63,10 +57,11 @@ public class HealthIndicatorAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(HealthAggregator.class) @ConditionalOnMissingBean(HealthAggregator.class)
public OrderedHealthAggregator healthAggregator() { public OrderedHealthAggregator healthAggregator(
HealthIndicatorProperties properties) {
OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator(); OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator();
if (this.properties.getOrder() != null) { if (properties.getOrder() != null) {
healthAggregator.setStatusOrder(this.properties.getOrder()); healthAggregator.setStatusOrder(properties.getOrder());
} }
return healthAggregator; return healthAggregator;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -50,16 +50,10 @@ import org.springframework.context.annotation.Configuration;
public class InfluxDbHealthIndicatorAutoConfiguration public class InfluxDbHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<InfluxDbHealthIndicator, InfluxDB> { extends CompositeHealthIndicatorConfiguration<InfluxDbHealthIndicator, InfluxDB> {
private final Map<String, InfluxDB> influxDbs;
public InfluxDbHealthIndicatorAutoConfiguration(Map<String, InfluxDB> influxDbs) {
this.influxDbs = influxDbs;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "influxDbHealthIndicator") @ConditionalOnMissingBean(name = "influxDbHealthIndicator")
public HealthIndicator influxDbHealthIndicator() { public HealthIndicator influxDbHealthIndicator(Map<String, InfluxDB> influxDbs) {
return createHealthIndicator(this.influxDbs); return createHealthIndicator(influxDbs);
} }
} }

View File

@ -66,19 +66,28 @@ public class DataSourceHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<DataSourceHealthIndicator, DataSource> CompositeHealthIndicatorConfiguration<DataSourceHealthIndicator, DataSource>
implements InitializingBean { implements InitializingBean {
private final Map<String, DataSource> dataSources;
private final Collection<DataSourcePoolMetadataProvider> metadataProviders; private final Collection<DataSourcePoolMetadataProvider> metadataProviders;
private DataSourcePoolMetadataProvider poolMetadataProvider; private DataSourcePoolMetadataProvider poolMetadataProvider;
public DataSourceHealthIndicatorAutoConfiguration(Map<String, DataSource> dataSources, public DataSourceHealthIndicatorAutoConfiguration(Map<String, DataSource> dataSources,
ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) {
this.dataSources = filterDataSources(dataSources);
this.metadataProviders = metadataProviders.orderedStream() this.metadataProviders = metadataProviders.orderedStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public void afterPropertiesSet() throws Exception {
this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(
this.metadataProviders);
}
@Bean
@ConditionalOnMissingBean(name = "dbHealthIndicator")
public HealthIndicator dbHealthIndicator(Map<String, DataSource> dataSources) {
return createHealthIndicator(filterDataSources(dataSources));
}
private Map<String, DataSource> filterDataSources( private Map<String, DataSource> filterDataSources(
Map<String, DataSource> candidates) { Map<String, DataSource> candidates) {
if (candidates == null) { if (candidates == null) {
@ -93,18 +102,6 @@ public class DataSourceHealthIndicatorAutoConfiguration extends
return dataSources; return dataSources;
} }
@Override
public void afterPropertiesSet() throws Exception {
this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(
this.metadataProviders);
}
@Bean
@ConditionalOnMissingBean(name = "dbHealthIndicator")
public HealthIndicator dbHealthIndicator() {
return createHealthIndicator(this.dataSources);
}
@Override @Override
protected DataSourceHealthIndicator createHealthIndicator(DataSource source) { protected DataSourceHealthIndicator createHealthIndicator(DataSource source) {
return new DataSourceHealthIndicator(source, getValidationQuery(source)); return new DataSourceHealthIndicator(source, getValidationQuery(source));

View File

@ -51,17 +51,11 @@ import org.springframework.context.annotation.Configuration;
public class JmsHealthIndicatorAutoConfiguration extends public class JmsHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<JmsHealthIndicator, ConnectionFactory> { CompositeHealthIndicatorConfiguration<JmsHealthIndicator, ConnectionFactory> {
private final Map<String, ConnectionFactory> connectionFactories;
public JmsHealthIndicatorAutoConfiguration(
Map<String, ConnectionFactory> connectionFactories) {
this.connectionFactories = connectionFactories;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "jmsHealthIndicator") @ConditionalOnMissingBean(name = "jmsHealthIndicator")
public HealthIndicator jmsHealthIndicator() { public HealthIndicator jmsHealthIndicator(
return createHealthIndicator(this.connectionFactories); Map<String, ConnectionFactory> connectionFactories) {
return createHealthIndicator(connectionFactories);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -50,17 +50,11 @@ import org.springframework.ldap.core.LdapOperations;
public class LdapHealthIndicatorAutoConfiguration extends public class LdapHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<LdapHealthIndicator, LdapOperations> { CompositeHealthIndicatorConfiguration<LdapHealthIndicator, LdapOperations> {
private final Map<String, LdapOperations> ldapOperations;
public LdapHealthIndicatorAutoConfiguration(
Map<String, LdapOperations> ldapOperations) {
this.ldapOperations = ldapOperations;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "ldapHealthIndicator") @ConditionalOnMissingBean(name = "ldapHealthIndicator")
public HealthIndicator ldapHealthIndicator() { public HealthIndicator ldapHealthIndicator(
return createHealthIndicator(this.ldapOperations); Map<String, LdapOperations> ldapOperations) {
return createHealthIndicator(ldapOperations);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,17 +43,12 @@ import org.springframework.util.StringUtils;
@EnableConfigurationProperties(LogFileWebEndpointProperties.class) @EnableConfigurationProperties(LogFileWebEndpointProperties.class)
public class LogFileWebEndpointAutoConfiguration { public class LogFileWebEndpointAutoConfiguration {
private final LogFileWebEndpointProperties properties;
public LogFileWebEndpointAutoConfiguration(LogFileWebEndpointProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(LogFileCondition.class) @Conditional(LogFileCondition.class)
public LogFileWebEndpoint logFileWebEndpoint(Environment environment) { public LogFileWebEndpoint logFileWebEndpoint(Environment environment,
return new LogFileWebEndpoint(environment, this.properties.getExternalFile()); LogFileWebEndpointProperties properties) {
return new LogFileWebEndpoint(environment, properties.getExternalFile());
} }
private static class LogFileCondition extends SpringBootCondition { private static class LogFileCondition extends SpringBootCondition {

View File

@ -49,17 +49,11 @@ import org.springframework.mail.javamail.JavaMailSenderImpl;
public class MailHealthIndicatorAutoConfiguration extends public class MailHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<MailHealthIndicator, JavaMailSenderImpl> { CompositeHealthIndicatorConfiguration<MailHealthIndicator, JavaMailSenderImpl> {
private final Map<String, JavaMailSenderImpl> mailSenders;
public MailHealthIndicatorAutoConfiguration(
Map<String, JavaMailSenderImpl> mailSenders) {
this.mailSenders = mailSenders;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "mailHealthIndicator") @ConditionalOnMissingBean(name = "mailHealthIndicator")
public HealthIndicator mailHealthIndicator() { public HealthIndicator mailHealthIndicator(
return createHealthIndicator(this.mailSenders); Map<String, JavaMailSenderImpl> mailSenders) {
return createHealthIndicator(mailSenders);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,9 @@ package org.springframework.boot.actuate.autoconfigure.metrics.jdbc;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -28,6 +30,7 @@ import io.micrometer.core.instrument.MeterRegistry;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
@ -62,25 +65,22 @@ public class DataSourcePoolMetricsAutoConfiguration {
private static final String DATASOURCE_SUFFIX = "dataSource"; private static final String DATASOURCE_SUFFIX = "dataSource";
private final MeterRegistry registry;
private final Collection<DataSourcePoolMetadataProvider> metadataProviders;
DataSourcePoolMetadataMetricsConfiguration(MeterRegistry registry,
Collection<DataSourcePoolMetadataProvider> metadataProviders) {
this.registry = registry;
this.metadataProviders = metadataProviders;
}
@Autowired @Autowired
public void bindDataSourcesToRegistry(Map<String, DataSource> dataSources) { public void bindDataSourcesToRegistry(Map<String, DataSource> dataSources,
dataSources.forEach(this::bindDataSourceToRegistry); MeterRegistry registry,
ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) {
List<DataSourcePoolMetadataProvider> metadataProvidersList = metadataProviders
.stream().collect(Collectors.toList());
dataSources.forEach((name, dataSource) -> bindDataSourceToRegistry(name,
dataSource, metadataProvidersList, registry));
} }
private void bindDataSourceToRegistry(String beanName, DataSource dataSource) { private void bindDataSourceToRegistry(String beanName, DataSource dataSource,
Collection<DataSourcePoolMetadataProvider> metadataProviders,
MeterRegistry registry) {
String dataSourceName = getDataSourceName(beanName); String dataSourceName = getDataSourceName(beanName);
new DataSourcePoolMetrics(dataSource, this.metadataProviders, dataSourceName, new DataSourcePoolMetrics(dataSource, metadataProviders, dataSourceName,
Collections.emptyList()).bindTo(this.registry); Collections.emptyList()).bindTo(registry);
} }
/** /**

View File

@ -54,23 +54,19 @@ public class HibernateMetricsAutoConfiguration {
private static final String ENTITY_MANAGER_FACTORY_SUFFIX = "entityManagerFactory"; private static final String ENTITY_MANAGER_FACTORY_SUFFIX = "entityManagerFactory";
private final MeterRegistry registry;
public HibernateMetricsAutoConfiguration(MeterRegistry registry) {
this.registry = registry;
}
@Autowired @Autowired
public void bindEntityManagerFactoriesToRegistry( public void bindEntityManagerFactoriesToRegistry(
Map<String, EntityManagerFactory> entityManagerFactories) { Map<String, EntityManagerFactory> entityManagerFactories,
entityManagerFactories.forEach(this::bindEntityManagerFactoryToRegistry); MeterRegistry registry) {
entityManagerFactories.forEach((name,
factory) -> bindEntityManagerFactoryToRegistry(name, factory, registry));
} }
private void bindEntityManagerFactoryToRegistry(String beanName, private void bindEntityManagerFactoryToRegistry(String beanName,
EntityManagerFactory entityManagerFactory) { EntityManagerFactory entityManagerFactory, MeterRegistry registry) {
String entityManagerFactoryName = getEntityManagerFactoryName(beanName); String entityManagerFactoryName = getEntityManagerFactoryName(beanName);
new HibernateMetrics(entityManagerFactory, entityManagerFactoryName, new HibernateMetrics(entityManagerFactory, entityManagerFactoryName,
Collections.emptyList()).bindTo(this.registry); Collections.emptyList()).bindTo(registry);
} }
/** /**

View File

@ -50,21 +50,15 @@ import org.springframework.core.annotation.Order;
@Import({ RestTemplateMetricsConfiguration.class, WebClientMetricsConfiguration.class }) @Import({ RestTemplateMetricsConfiguration.class, WebClientMetricsConfiguration.class })
public class HttpClientMetricsAutoConfiguration { public class HttpClientMetricsAutoConfiguration {
private final MetricsProperties properties;
public HttpClientMetricsAutoConfiguration(MetricsProperties properties) {
this.properties = properties;
}
@Bean @Bean
@Order(0) @Order(0)
public MeterFilter metricsHttpClientUriTagFilter() { public MeterFilter metricsHttpClientUriTagFilter(MetricsProperties properties) {
String metricName = this.properties.getWeb().getClient().getRequestsMetricName(); String metricName = properties.getWeb().getClient().getRequestsMetricName();
MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter(() -> String MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter(() -> String
.format("Reached the maximum number of URI tags for '%s'. Are you using " .format("Reached the maximum number of URI tags for '%s'. Are you using "
+ "'uriVariables'?", metricName)); + "'uriVariables'?", metricName));
return MeterFilter.maximumAllowableTags(metricName, "uri", return MeterFilter.maximumAllowableTags(metricName, "uri",
this.properties.getWeb().getClient().getMaxUriTags(), denyFilter); properties.getWeb().getClient().getMaxUriTags(), denyFilter);
} }
} }

View File

@ -42,12 +42,6 @@ import org.springframework.web.client.RestTemplate;
@ConditionalOnBean(RestTemplateBuilder.class) @ConditionalOnBean(RestTemplateBuilder.class)
class RestTemplateMetricsConfiguration { class RestTemplateMetricsConfiguration {
private final MetricsProperties properties;
RestTemplateMetricsConfiguration(MetricsProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean(RestTemplateExchangeTagsProvider.class) @ConditionalOnMissingBean(RestTemplateExchangeTagsProvider.class)
public DefaultRestTemplateExchangeTagsProvider restTemplateExchangeTagsProvider() { public DefaultRestTemplateExchangeTagsProvider restTemplateExchangeTagsProvider() {
@ -57,10 +51,11 @@ class RestTemplateMetricsConfiguration {
@Bean @Bean
public MetricsRestTemplateCustomizer metricsRestTemplateCustomizer( public MetricsRestTemplateCustomizer metricsRestTemplateCustomizer(
MeterRegistry meterRegistry, MeterRegistry meterRegistry,
RestTemplateExchangeTagsProvider restTemplateExchangeTagsProvider) { RestTemplateExchangeTagsProvider restTemplateExchangeTagsProvider,
MetricsProperties properties) {
return new MetricsRestTemplateCustomizer(meterRegistry, return new MetricsRestTemplateCustomizer(meterRegistry,
restTemplateExchangeTagsProvider, restTemplateExchangeTagsProvider,
this.properties.getWeb().getClient().getRequestsMetricName()); properties.getWeb().getClient().getRequestsMetricName());
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -51,16 +51,11 @@ import org.springframework.data.mongodb.core.MongoTemplate;
public class MongoHealthIndicatorAutoConfiguration extends public class MongoHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<MongoHealthIndicator, MongoTemplate> { CompositeHealthIndicatorConfiguration<MongoHealthIndicator, MongoTemplate> {
private final Map<String, MongoTemplate> mongoTemplates;
MongoHealthIndicatorAutoConfiguration(Map<String, MongoTemplate> mongoTemplates) {
this.mongoTemplates = mongoTemplates;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "mongoHealthIndicator") @ConditionalOnMissingBean(name = "mongoHealthIndicator")
public HealthIndicator mongoHealthIndicator() { public HealthIndicator mongoHealthIndicator(
return createHealthIndicator(this.mongoTemplates); Map<String, MongoTemplate> mongoTemplates) {
return createHealthIndicator(mongoTemplates);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,17 +52,11 @@ import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
public class MongoReactiveHealthIndicatorAutoConfiguration extends public class MongoReactiveHealthIndicatorAutoConfiguration extends
CompositeReactiveHealthIndicatorConfiguration<MongoReactiveHealthIndicator, ReactiveMongoTemplate> { CompositeReactiveHealthIndicatorConfiguration<MongoReactiveHealthIndicator, ReactiveMongoTemplate> {
private final Map<String, ReactiveMongoTemplate> reactiveMongoTemplate;
MongoReactiveHealthIndicatorAutoConfiguration(
Map<String, ReactiveMongoTemplate> reactiveMongoTemplate) {
this.reactiveMongoTemplate = reactiveMongoTemplate;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "mongoHealthIndicator") @ConditionalOnMissingBean(name = "mongoHealthIndicator")
public ReactiveHealthIndicator mongoHealthIndicator() { public ReactiveHealthIndicator mongoHealthIndicator(
return createHealthIndicator(this.reactiveMongoTemplate); Map<String, ReactiveMongoTemplate> reactiveMongoTemplates) {
return createHealthIndicator(reactiveMongoTemplates);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -51,17 +51,11 @@ import org.springframework.context.annotation.Configuration;
public class Neo4jHealthIndicatorAutoConfiguration extends public class Neo4jHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<Neo4jHealthIndicator, SessionFactory> { CompositeHealthIndicatorConfiguration<Neo4jHealthIndicator, SessionFactory> {
private final Map<String, SessionFactory> sessionFactories;
public Neo4jHealthIndicatorAutoConfiguration(
Map<String, SessionFactory> sessionFactories) {
this.sessionFactories = sessionFactories;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "neo4jHealthIndicator") @ConditionalOnMissingBean(name = "neo4jHealthIndicator")
public HealthIndicator neo4jHealthIndicator() { public HealthIndicator neo4jHealthIndicator(
return createHealthIndicator(this.sessionFactories); Map<String, SessionFactory> sessionFactories) {
return createHealthIndicator(sessionFactories);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,17 +53,11 @@ import org.springframework.data.redis.connection.RedisConnectionFactory;
public class RedisHealthIndicatorAutoConfiguration extends public class RedisHealthIndicatorAutoConfiguration extends
CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> { CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {
private final Map<String, RedisConnectionFactory> redisConnectionFactories;
public RedisHealthIndicatorAutoConfiguration(
Map<String, RedisConnectionFactory> redisConnectionFactories) {
this.redisConnectionFactories = redisConnectionFactories;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "redisHealthIndicator") @ConditionalOnMissingBean(name = "redisHealthIndicator")
public HealthIndicator redisHealthIndicator() { public HealthIndicator redisHealthIndicator(
return createHealthIndicator(this.redisConnectionFactories); Map<String, RedisConnectionFactory> redisConnectionFactories) {
return createHealthIndicator(redisConnectionFactories);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -51,16 +51,10 @@ import org.springframework.context.annotation.Configuration;
public class SolrHealthIndicatorAutoConfiguration public class SolrHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<SolrHealthIndicator, SolrClient> { extends CompositeHealthIndicatorConfiguration<SolrHealthIndicator, SolrClient> {
private final Map<String, SolrClient> solrClients;
public SolrHealthIndicatorAutoConfiguration(Map<String, SolrClient> solrClients) {
this.solrClients = solrClients;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "solrHealthIndicator") @ConditionalOnMissingBean(name = "solrHealthIndicator")
public HealthIndicator solrHealthIndicator() { public HealthIndicator solrHealthIndicator(Map<String, SolrClient> solrClients) {
return createHealthIndicator(this.solrClients); return createHealthIndicator(solrClients);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -55,24 +55,14 @@ public class SpringApplicationAdminJmxAutoConfiguration {
*/ */
private static final String DEFAULT_JMX_NAME = "org.springframework.boot:type=Admin,name=SpringApplication"; private static final String DEFAULT_JMX_NAME = "org.springframework.boot:type=Admin,name=SpringApplication";
private final Iterable<MBeanExporter> mbeanExporters;
private final Environment environment;
public SpringApplicationAdminJmxAutoConfiguration(
ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) {
this.mbeanExporters = mbeanExporters;
this.environment = environment;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar() public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar(
ObjectProvider<MBeanExporter> mbeanExporters, Environment environment)
throws MalformedObjectNameException { throws MalformedObjectNameException {
String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY, String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME);
DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice
if (this.mbeanExporters != null) { // Make sure to not register that MBean twice for (MBeanExporter mbeanExporter : mbeanExporters) {
for (MBeanExporter mbeanExporter : this.mbeanExporters) {
mbeanExporter.addExcludedBean(jmxName); mbeanExporter.addExcludedBean(jmxName);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -157,53 +157,39 @@ public class RabbitAutoConfiguration {
@Import(RabbitConnectionFactoryCreator.class) @Import(RabbitConnectionFactoryCreator.class)
protected static class RabbitTemplateConfiguration { protected static class RabbitTemplateConfiguration {
private final RabbitProperties properties;
private final ObjectProvider<MessageConverter> messageConverter;
private final ObjectProvider<RabbitRetryTemplateCustomizer> retryTemplateCustomizers;
public RabbitTemplateConfiguration(RabbitProperties properties,
ObjectProvider<MessageConverter> messageConverter,
ObjectProvider<RabbitRetryTemplateCustomizer> retryTemplateCustomizers) {
this.properties = properties;
this.messageConverter = messageConverter;
this.retryTemplateCustomizers = retryTemplateCustomizers;
}
@Bean @Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnMissingBean @ConditionalOnMissingBean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { public RabbitTemplate rabbitTemplate(RabbitProperties properties,
ObjectProvider<MessageConverter> messageConverter,
ObjectProvider<RabbitRetryTemplateCustomizer> retryTemplateCustomizers,
ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
RabbitTemplate template = new RabbitTemplate(connectionFactory); RabbitTemplate template = new RabbitTemplate(connectionFactory);
MessageConverter messageConverter = this.messageConverter.getIfUnique(); messageConverter.ifUnique(template::setMessageConverter);
if (messageConverter != null) { template.setMandatory(determineMandatoryFlag(properties));
template.setMessageConverter(messageConverter); RabbitProperties.Template templateProperties = properties.getTemplate();
} if (templateProperties.getRetry().isEnabled()) {
template.setMandatory(determineMandatoryFlag()); template.setRetryTemplate(
RabbitProperties.Template properties = this.properties.getTemplate(); new RetryTemplateFactory(retryTemplateCustomizers.orderedStream()
if (properties.getRetry().isEnabled()) {
template.setRetryTemplate(new RetryTemplateFactory(
this.retryTemplateCustomizers.orderedStream()
.collect(Collectors.toList())).createRetryTemplate( .collect(Collectors.toList())).createRetryTemplate(
properties.getRetry(), templateProperties.getRetry(),
RabbitRetryTemplateCustomizer.Target.SENDER)); RabbitRetryTemplateCustomizer.Target.SENDER));
} }
map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) map.from(templateProperties::getReceiveTimeout).whenNonNull()
.to(template::setReceiveTimeout); .as(Duration::toMillis).to(template::setReceiveTimeout);
map.from(properties::getReplyTimeout).whenNonNull().as(Duration::toMillis) map.from(templateProperties::getReplyTimeout).whenNonNull()
.to(template::setReplyTimeout); .as(Duration::toMillis).to(template::setReplyTimeout);
map.from(properties::getExchange).to(template::setExchange); map.from(templateProperties::getExchange).to(template::setExchange);
map.from(properties::getRoutingKey).to(template::setRoutingKey); map.from(templateProperties::getRoutingKey).to(template::setRoutingKey);
map.from(properties::getDefaultReceiveQueue).whenNonNull() map.from(templateProperties::getDefaultReceiveQueue).whenNonNull()
.to(template::setDefaultReceiveQueue); .to(template::setDefaultReceiveQueue);
return template; return template;
} }
private boolean determineMandatoryFlag() { private boolean determineMandatoryFlag(RabbitProperties properties) {
Boolean mandatory = this.properties.getTemplate().getMandatory(); Boolean mandatory = properties.getTemplate().getMandatory();
return (mandatory != null) ? mandatory : this.properties.isPublisherReturns(); return (mandatory != null) ? mandatory : properties.isPublisherReturns();
} }
@Bean @Bean

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -68,12 +68,8 @@ public class BatchAutoConfiguration {
private final BatchProperties properties; private final BatchProperties properties;
private final JobParametersConverter jobParametersConverter; public BatchAutoConfiguration(BatchProperties properties) {
public BatchAutoConfiguration(BatchProperties properties,
ObjectProvider<JobParametersConverter> jobParametersConverter) {
this.properties = properties; this.properties = properties;
this.jobParametersConverter = jobParametersConverter.getIfAvailable();
} }
@Bean @Bean
@ -108,7 +104,9 @@ public class BatchAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(JobOperator.class) @ConditionalOnMissingBean(JobOperator.class)
public SimpleJobOperator jobOperator(JobExplorer jobExplorer, JobLauncher jobLauncher, public SimpleJobOperator jobOperator(
ObjectProvider<JobParametersConverter> jobParametersConverter,
JobExplorer jobExplorer, JobLauncher jobLauncher,
ListableJobLocator jobRegistry, JobRepository jobRepository) ListableJobLocator jobRegistry, JobRepository jobRepository)
throws Exception { throws Exception {
SimpleJobOperator factory = new SimpleJobOperator(); SimpleJobOperator factory = new SimpleJobOperator();
@ -116,9 +114,7 @@ public class BatchAutoConfiguration {
factory.setJobLauncher(jobLauncher); factory.setJobLauncher(jobLauncher);
factory.setJobRegistry(jobRegistry); factory.setJobRegistry(jobRegistry);
factory.setJobRepository(jobRepository); factory.setJobRepository(jobRepository);
if (this.jobParametersConverter != null) { jobParametersConverter.ifAvailable(factory::setJobParametersConverter);
factory.setJobParametersConverter(this.jobParametersConverter);
}
return factory; return factory;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -45,57 +45,44 @@ import org.springframework.util.StringUtils;
@Conditional({ CacheCondition.class }) @Conditional({ CacheCondition.class })
class CaffeineCacheConfiguration { class CaffeineCacheConfiguration {
private final CacheProperties cacheProperties; @Bean
public CaffeineCacheManager cacheManager(CacheProperties cacheProperties,
private final CacheManagerCustomizers customizers;
private final Caffeine<Object, Object> caffeine;
private final CaffeineSpec caffeineSpec;
private final CacheLoader<Object, Object> cacheLoader;
CaffeineCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers, CacheManagerCustomizers customizers,
ObjectProvider<Caffeine<Object, Object>> caffeine, ObjectProvider<Caffeine<Object, Object>> caffeine,
ObjectProvider<CaffeineSpec> caffeineSpec, ObjectProvider<CaffeineSpec> caffeineSpec,
ObjectProvider<CacheLoader<Object, Object>> cacheLoader) { ObjectProvider<CacheLoader<Object, Object>> cacheLoader) {
this.cacheProperties = cacheProperties; CaffeineCacheManager cacheManager = createCacheManager(cacheProperties, caffeine,
this.customizers = customizers; caffeineSpec, cacheLoader);
this.caffeine = caffeine.getIfAvailable(); List<String> cacheNames = cacheProperties.getCacheNames();
this.caffeineSpec = caffeineSpec.getIfAvailable();
this.cacheLoader = cacheLoader.getIfAvailable();
}
@Bean
public CaffeineCacheManager cacheManager() {
CaffeineCacheManager cacheManager = createCacheManager();
List<String> cacheNames = this.cacheProperties.getCacheNames();
if (!CollectionUtils.isEmpty(cacheNames)) { if (!CollectionUtils.isEmpty(cacheNames)) {
cacheManager.setCacheNames(cacheNames); cacheManager.setCacheNames(cacheNames);
} }
return this.customizers.customize(cacheManager); return customizers.customize(cacheManager);
} }
private CaffeineCacheManager createCacheManager() { private CaffeineCacheManager createCacheManager(CacheProperties cacheProperties,
ObjectProvider<Caffeine<Object, Object>> caffeine,
ObjectProvider<CaffeineSpec> caffeineSpec,
ObjectProvider<CacheLoader<Object, Object>> cacheLoader) {
CaffeineCacheManager cacheManager = new CaffeineCacheManager(); CaffeineCacheManager cacheManager = new CaffeineCacheManager();
setCacheBuilder(cacheManager); setCacheBuilder(cacheProperties, caffeineSpec.getIfAvailable(),
if (this.cacheLoader != null) { caffeine.getIfAvailable(), cacheManager);
cacheManager.setCacheLoader(this.cacheLoader); cacheLoader.ifAvailable(cacheManager::setCacheLoader);
}
return cacheManager; return cacheManager;
} }
private void setCacheBuilder(CaffeineCacheManager cacheManager) { private void setCacheBuilder(CacheProperties cacheProperties,
String specification = this.cacheProperties.getCaffeine().getSpec(); CaffeineSpec caffeineSpec, Caffeine<Object, Object> caffeine,
CaffeineCacheManager cacheManager) {
String specification = cacheProperties.getCaffeine().getSpec();
if (StringUtils.hasText(specification)) { if (StringUtils.hasText(specification)) {
cacheManager.setCacheSpecification(specification); cacheManager.setCacheSpecification(specification);
} }
else if (this.caffeineSpec != null) { else if (caffeineSpec != null) {
cacheManager.setCaffeineSpec(this.caffeineSpec); cacheManager.setCaffeineSpec(caffeineSpec);
} }
else if (this.caffeine != null) { else if (caffeine != null) {
cacheManager.setCaffeine(this.caffeine); cacheManager.setCaffeine(caffeine);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,29 +47,17 @@ import org.springframework.util.StringUtils;
@Conditional(CacheCondition.class) @Conditional(CacheCondition.class)
public class CouchbaseCacheConfiguration { public class CouchbaseCacheConfiguration {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizers;
private final Bucket bucket;
public CouchbaseCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers, Bucket bucket) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
this.bucket = bucket;
}
@Bean @Bean
public CouchbaseCacheManager cacheManager() { public CouchbaseCacheManager cacheManager(CacheProperties cacheProperties,
List<String> cacheNames = this.cacheProperties.getCacheNames(); CacheManagerCustomizers customizers, Bucket bucket) {
CacheBuilder builder = CacheBuilder.newInstance(this.bucket); List<String> cacheNames = cacheProperties.getCacheNames();
Couchbase couchbase = this.cacheProperties.getCouchbase(); CacheBuilder builder = CacheBuilder.newInstance(bucket);
Couchbase couchbase = cacheProperties.getCouchbase();
PropertyMapper.get().from(couchbase::getExpiration).whenNonNull() PropertyMapper.get().from(couchbase::getExpiration).whenNonNull()
.asInt(Duration::getSeconds).to(builder::withExpiration); .asInt(Duration::getSeconds).to(builder::withExpiration);
String[] names = StringUtils.toStringArray(cacheNames); String[] names = StringUtils.toStringArray(cacheNames);
CouchbaseCacheManager cacheManager = new CouchbaseCacheManager(builder, names); CouchbaseCacheManager cacheManager = new CouchbaseCacheManager(builder, names);
return this.customizers.customize(cacheManager); return customizers.customize(cacheManager);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -45,26 +45,17 @@ import org.springframework.core.io.Resource;
EhCacheCacheConfiguration.ConfigAvailableCondition.class }) EhCacheCacheConfiguration.ConfigAvailableCondition.class })
class EhCacheCacheConfiguration { class EhCacheCacheConfiguration {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizers;
EhCacheCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
}
@Bean @Bean
public EhCacheCacheManager cacheManager(CacheManager ehCacheCacheManager) { public EhCacheCacheManager cacheManager(CacheManagerCustomizers customizers,
return this.customizers.customize(new EhCacheCacheManager(ehCacheCacheManager)); CacheManager ehCacheCacheManager) {
return customizers.customize(new EhCacheCacheManager(ehCacheCacheManager));
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public CacheManager ehCacheCacheManager() { public CacheManager ehCacheCacheManager(CacheProperties cacheProperties) {
Resource location = this.cacheProperties Resource location = cacheProperties
.resolveConfigLocation(this.cacheProperties.getEhcache().getConfig()); .resolveConfigLocation(cacheProperties.getEhcache().getConfig());
if (location != null) { if (location != null) {
return EhCacheManagerUtils.buildCacheManager(location); return EhCacheManagerUtils.buildCacheManager(location);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -40,17 +40,12 @@ import org.springframework.context.annotation.Configuration;
@Conditional(CacheCondition.class) @Conditional(CacheCondition.class)
class GenericCacheConfiguration { class GenericCacheConfiguration {
private final CacheManagerCustomizers customizers;
GenericCacheConfiguration(CacheManagerCustomizers customizers) {
this.customizers = customizers;
}
@Bean @Bean
public SimpleCacheManager cacheManager(Collection<Cache> caches) { public SimpleCacheManager cacheManager(CacheManagerCustomizers customizers,
Collection<Cache> caches) {
SimpleCacheManager cacheManager = new SimpleCacheManager(); SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(caches); cacheManager.setCaches(caches);
return this.customizers.customize(cacheManager); return customizers.customize(cacheManager);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -50,18 +50,12 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnSingleCandidate(HazelcastInstance.class) @ConditionalOnSingleCandidate(HazelcastInstance.class)
class HazelcastCacheConfiguration { class HazelcastCacheConfiguration {
private final CacheManagerCustomizers customizers;
HazelcastCacheConfiguration(CacheManagerCustomizers customizers) {
this.customizers = customizers;
}
@Bean @Bean
public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance) public HazelcastCacheManager cacheManager(CacheManagerCustomizers customizers,
throws IOException { HazelcastInstance existingHazelcastInstance) throws IOException {
HazelcastCacheManager cacheManager = new HazelcastCacheManager( HazelcastCacheManager cacheManager = new HazelcastCacheManager(
existingHazelcastInstance); existingHazelcastInstance);
return this.customizers.customize(cacheManager); return customizers.customize(cacheManager);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,43 +49,33 @@ import org.springframework.util.CollectionUtils;
@Conditional(CacheCondition.class) @Conditional(CacheCondition.class)
public class InfinispanCacheConfiguration { public class InfinispanCacheConfiguration {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizers;
private final ConfigurationBuilder defaultConfigurationBuilder;
public InfinispanCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers,
ObjectProvider<ConfigurationBuilder> defaultConfigurationBuilder) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
this.defaultConfigurationBuilder = defaultConfigurationBuilder.getIfAvailable();
}
@Bean @Bean
public SpringEmbeddedCacheManager cacheManager( public SpringEmbeddedCacheManager cacheManager(CacheManagerCustomizers customizers,
EmbeddedCacheManager embeddedCacheManager) { EmbeddedCacheManager embeddedCacheManager) {
SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager( SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager(
embeddedCacheManager); embeddedCacheManager);
return this.customizers.customize(cacheManager); return customizers.customize(cacheManager);
} }
@Bean(destroyMethod = "stop") @Bean(destroyMethod = "stop")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public EmbeddedCacheManager infinispanCacheManager() throws IOException { public EmbeddedCacheManager infinispanCacheManager(CacheProperties cacheProperties,
EmbeddedCacheManager cacheManager = createEmbeddedCacheManager(); ObjectProvider<ConfigurationBuilder> defaultConfigurationBuilder)
List<String> cacheNames = this.cacheProperties.getCacheNames(); throws IOException {
EmbeddedCacheManager cacheManager = createEmbeddedCacheManager(cacheProperties);
List<String> cacheNames = cacheProperties.getCacheNames();
if (!CollectionUtils.isEmpty(cacheNames)) { if (!CollectionUtils.isEmpty(cacheNames)) {
cacheNames.forEach((cacheName) -> cacheManager.defineConfiguration(cacheName, cacheNames.forEach((cacheName) -> cacheManager.defineConfiguration(cacheName,
getDefaultCacheConfiguration())); getDefaultCacheConfiguration(
defaultConfigurationBuilder.getIfAvailable())));
} }
return cacheManager; return cacheManager;
} }
private EmbeddedCacheManager createEmbeddedCacheManager() throws IOException { private EmbeddedCacheManager createEmbeddedCacheManager(
Resource location = this.cacheProperties CacheProperties cacheProperties) throws IOException {
.resolveConfigLocation(this.cacheProperties.getInfinispan().getConfig()); Resource location = cacheProperties
.resolveConfigLocation(cacheProperties.getInfinispan().getConfig());
if (location != null) { if (location != null) {
try (InputStream in = location.getInputStream()) { try (InputStream in = location.getInputStream()) {
return new DefaultCacheManager(in); return new DefaultCacheManager(in);
@ -94,9 +84,10 @@ public class InfinispanCacheConfiguration {
return new DefaultCacheManager(); return new DefaultCacheManager();
} }
private org.infinispan.configuration.cache.Configuration getDefaultCacheConfiguration() { private org.infinispan.configuration.cache.Configuration getDefaultCacheConfiguration(
if (this.defaultConfigurationBuilder != null) { ConfigurationBuilder defaultConfigurationBuilder) {
return this.defaultConfigurationBuilder.build(); if (defaultConfigurationBuilder != null) {
return defaultConfigurationBuilder.build();
} }
return new ConfigurationBuilder().build(); return new ConfigurationBuilder().build();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -63,61 +63,50 @@ import org.springframework.util.StringUtils;
@Import(HazelcastJCacheCustomizationConfiguration.class) @Import(HazelcastJCacheCustomizationConfiguration.class)
class JCacheCacheConfiguration implements BeanClassLoaderAware { class JCacheCacheConfiguration implements BeanClassLoaderAware {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizers;
private final javax.cache.configuration.Configuration<?, ?> defaultCacheConfiguration;
private final ObjectProvider<JCacheManagerCustomizer> cacheManagerCustomizers;
private final ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers;
private ClassLoader beanClassLoader; private ClassLoader beanClassLoader;
JCacheCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers,
ObjectProvider<javax.cache.configuration.Configuration<?, ?>> defaultCacheConfiguration,
ObjectProvider<JCacheManagerCustomizer> cacheManagerCustomizers,
ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
this.defaultCacheConfiguration = defaultCacheConfiguration.getIfAvailable();
this.cacheManagerCustomizers = cacheManagerCustomizers;
this.cachePropertiesCustomizers = cachePropertiesCustomizers;
}
@Override @Override
public void setBeanClassLoader(ClassLoader classLoader) { public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader; this.beanClassLoader = classLoader;
} }
@Bean @Bean
public JCacheCacheManager cacheManager(CacheManager jCacheCacheManager) { public JCacheCacheManager cacheManager(CacheManagerCustomizers customizers,
CacheManager jCacheCacheManager) {
JCacheCacheManager cacheManager = new JCacheCacheManager(jCacheCacheManager); JCacheCacheManager cacheManager = new JCacheCacheManager(jCacheCacheManager);
return this.customizers.customize(cacheManager); return customizers.customize(cacheManager);
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public CacheManager jCacheCacheManager() throws IOException { public CacheManager jCacheCacheManager(CacheProperties cacheProperties,
CacheManager jCacheCacheManager = createCacheManager(); ObjectProvider<javax.cache.configuration.Configuration<?, ?>> defaultCacheConfiguration,
List<String> cacheNames = this.cacheProperties.getCacheNames(); ObjectProvider<JCacheManagerCustomizer> cacheManagerCustomizers,
ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers)
throws IOException {
CacheManager jCacheCacheManager = createCacheManager(cacheProperties,
cachePropertiesCustomizers);
List<String> cacheNames = cacheProperties.getCacheNames();
if (!CollectionUtils.isEmpty(cacheNames)) { if (!CollectionUtils.isEmpty(cacheNames)) {
for (String cacheName : cacheNames) { for (String cacheName : cacheNames) {
jCacheCacheManager.createCache(cacheName, getDefaultCacheConfiguration()); jCacheCacheManager.createCache(cacheName, defaultCacheConfiguration
.getIfAvailable(MutableConfiguration::new));
} }
} }
customize(jCacheCacheManager); cacheManagerCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(jCacheCacheManager));
return jCacheCacheManager; return jCacheCacheManager;
} }
private CacheManager createCacheManager() throws IOException { private CacheManager createCacheManager(CacheProperties cacheProperties,
ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers)
throws IOException {
CachingProvider cachingProvider = getCachingProvider( CachingProvider cachingProvider = getCachingProvider(
this.cacheProperties.getJcache().getProvider()); cacheProperties.getJcache().getProvider());
Properties properties = createCacheManagerProperties(); Properties properties = createCacheManagerProperties(cachePropertiesCustomizers,
Resource configLocation = this.cacheProperties cacheProperties);
.resolveConfigLocation(this.cacheProperties.getJcache().getConfig()); Resource configLocation = cacheProperties
.resolveConfigLocation(cacheProperties.getJcache().getConfig());
if (configLocation != null) { if (configLocation != null) {
return cachingProvider.getCacheManager(configLocation.getURI(), return cachingProvider.getCacheManager(configLocation.getURI(),
this.beanClassLoader, properties); this.beanClassLoader, properties);
@ -132,25 +121,15 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware {
return Caching.getCachingProvider(); return Caching.getCachingProvider();
} }
private Properties createCacheManagerProperties() { private Properties createCacheManagerProperties(
ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers,
CacheProperties cacheProperties) {
Properties properties = new Properties(); Properties properties = new Properties();
this.cachePropertiesCustomizers.orderedStream().forEach( cachePropertiesCustomizers.orderedStream().forEach(
(customizer) -> customizer.customize(this.cacheProperties, properties)); (customizer) -> customizer.customize(cacheProperties, properties));
return properties; return properties;
} }
private javax.cache.configuration.Configuration<?, ?> getDefaultCacheConfiguration() {
if (this.defaultCacheConfiguration != null) {
return this.defaultCacheConfiguration;
}
return new MutableConfiguration<>();
}
private void customize(CacheManager cacheManager) {
this.cacheManagerCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(cacheManager));
}
/** /**
* Determine if JCache is available. This either kicks in if a provider is available * Determine if JCache is available. This either kicks in if a provider is available
* as defined per {@link JCacheProviderAvailableCondition} or if a * as defined per {@link JCacheProviderAvailableCondition} or if a

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,39 +53,35 @@ import org.springframework.data.redis.serializer.RedisSerializationContext.Seria
@Conditional(CacheCondition.class) @Conditional(CacheCondition.class)
class RedisCacheConfiguration { class RedisCacheConfiguration {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizerInvoker;
private final org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration;
RedisCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizerInvoker,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration) {
this.cacheProperties = cacheProperties;
this.customizerInvoker = customizerInvoker;
this.redisCacheConfiguration = redisCacheConfiguration.getIfAvailable();
}
@Bean @Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, public RedisCacheManager cacheManager(CacheProperties cacheProperties,
CacheManagerCustomizers cacheManagerCustomizers,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
RedisConnectionFactory redisConnectionFactory,
ResourceLoader resourceLoader) { ResourceLoader resourceLoader) {
RedisCacheManagerBuilder builder = RedisCacheManager RedisCacheManagerBuilder builder = RedisCacheManager
.builder(redisConnectionFactory) .builder(redisConnectionFactory)
.cacheDefaults(determineConfiguration(resourceLoader.getClassLoader())); .cacheDefaults(determineConfiguration(cacheProperties,
List<String> cacheNames = this.cacheProperties.getCacheNames(); redisCacheConfiguration, resourceLoader.getClassLoader()));
List<String> cacheNames = cacheProperties.getCacheNames();
if (!cacheNames.isEmpty()) { if (!cacheNames.isEmpty()) {
builder.initialCacheNames(new LinkedHashSet<>(cacheNames)); builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
} }
return this.customizerInvoker.customize(builder.build()); return cacheManagerCustomizers.customize(builder.build());
} }
private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration( private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(
CacheProperties cacheProperties,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
ClassLoader classLoader) { ClassLoader classLoader) {
if (this.redisCacheConfiguration != null) { return redisCacheConfiguration
return this.redisCacheConfiguration; .getIfAvailable(() -> createConfiguration(cacheProperties, classLoader));
}
Redis redisProperties = this.cacheProperties.getRedis(); }
private org.springframework.data.redis.cache.RedisCacheConfiguration createConfiguration(
CacheProperties cacheProperties, ClassLoader classLoader) {
Redis redisProperties = cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig(); .defaultCacheConfig();
config = config.serializeValuesWith(SerializationPair config = config.serializeValuesWith(SerializationPair

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -36,24 +36,15 @@ import org.springframework.context.annotation.Configuration;
@Conditional(CacheCondition.class) @Conditional(CacheCondition.class)
class SimpleCacheConfiguration { class SimpleCacheConfiguration {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizerInvoker;
SimpleCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizerInvoker) {
this.cacheProperties = cacheProperties;
this.customizerInvoker = customizerInvoker;
}
@Bean @Bean
public ConcurrentMapCacheManager cacheManager() { public ConcurrentMapCacheManager cacheManager(CacheProperties cacheProperties,
CacheManagerCustomizers cacheManagerCustomizers) {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
List<String> cacheNames = this.cacheProperties.getCacheNames(); List<String> cacheNames = cacheProperties.getCacheNames();
if (!cacheNames.isEmpty()) { if (!cacheNames.isEmpty()) {
cacheManager.setCacheNames(cacheNames); cacheManager.setCacheNames(cacheNames);
} }
return this.customizerInvoker.customize(cacheManager); return cacheManagerCustomizers.customize(cacheManager);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -48,22 +48,12 @@ import org.springframework.util.StringUtils;
@EnableConfigurationProperties(CassandraProperties.class) @EnableConfigurationProperties(CassandraProperties.class)
public class CassandraAutoConfiguration { public class CassandraAutoConfiguration {
private final CassandraProperties properties;
private final ObjectProvider<ClusterBuilderCustomizer> builderCustomizers;
public CassandraAutoConfiguration(CassandraProperties properties,
ObjectProvider<ClusterBuilderCustomizer> builderCustomizers) {
this.properties = properties;
this.builderCustomizers = builderCustomizers;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Cluster cassandraCluster() { public Cluster cassandraCluster(CassandraProperties properties,
ObjectProvider<ClusterBuilderCustomizer> builderCustomizers) {
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
CassandraProperties properties = this.properties;
Cluster.Builder builder = Cluster.builder() Cluster.Builder builder = Cluster.builder()
.withClusterName(properties.getClusterName()) .withClusterName(properties.getClusterName())
.withPort(properties.getPort()); .withPort(properties.getPort());
@ -72,31 +62,29 @@ public class CassandraAutoConfiguration {
map.from(properties::getCompression).whenNonNull().to(builder::withCompression); map.from(properties::getCompression).whenNonNull().to(builder::withCompression);
map.from(properties::getLoadBalancingPolicy).whenNonNull() map.from(properties::getLoadBalancingPolicy).whenNonNull()
.as(BeanUtils::instantiateClass).to(builder::withLoadBalancingPolicy); .as(BeanUtils::instantiateClass).to(builder::withLoadBalancingPolicy);
map.from(this::getQueryOptions).to(builder::withQueryOptions); QueryOptions queryOptions = getQueryOptions(properties);
map.from(queryOptions).to(builder::withQueryOptions);
map.from(properties::getReconnectionPolicy).whenNonNull() map.from(properties::getReconnectionPolicy).whenNonNull()
.as(BeanUtils::instantiateClass).to(builder::withReconnectionPolicy); .as(BeanUtils::instantiateClass).to(builder::withReconnectionPolicy);
map.from(properties::getRetryPolicy).whenNonNull().as(BeanUtils::instantiateClass) map.from(properties::getRetryPolicy).whenNonNull().as(BeanUtils::instantiateClass)
.to(builder::withRetryPolicy); .to(builder::withRetryPolicy);
map.from(this::getSocketOptions).to(builder::withSocketOptions); SocketOptions socketOptions = getSocketOptions(properties);
map.from(socketOptions).to(builder::withSocketOptions);
map.from(properties::isSsl).whenTrue().toCall(builder::withSSL); map.from(properties::isSsl).whenTrue().toCall(builder::withSSL);
map.from(this::getPoolingOptions).to(builder::withPoolingOptions); PoolingOptions poolingOptions = getPoolingOptions(properties);
map.from(poolingOptions).to(builder::withPoolingOptions);
map.from(properties::getContactPoints).as(StringUtils::toStringArray) map.from(properties::getContactPoints).as(StringUtils::toStringArray)
.to(builder::addContactPoints); .to(builder::addContactPoints);
map.from(properties::isJmxEnabled).whenFalse() map.from(properties::isJmxEnabled).whenFalse()
.toCall(builder::withoutJMXReporting); .toCall(builder::withoutJMXReporting);
customize(builder); builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
return builder.build(); return builder.build();
} }
private void customize(Cluster.Builder builder) { private QueryOptions getQueryOptions(CassandraProperties properties) {
this.builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
}
private QueryOptions getQueryOptions() {
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
QueryOptions options = new QueryOptions(); QueryOptions options = new QueryOptions();
CassandraProperties properties = this.properties;
map.from(properties::getConsistencyLevel).whenNonNull() map.from(properties::getConsistencyLevel).whenNonNull()
.to(options::setConsistencyLevel); .to(options::setConsistencyLevel);
map.from(properties::getSerialConsistencyLevel).whenNonNull() map.from(properties::getSerialConsistencyLevel).whenNonNull()
@ -105,27 +93,27 @@ public class CassandraAutoConfiguration {
return options; return options;
} }
private SocketOptions getSocketOptions() { private SocketOptions getSocketOptions(CassandraProperties properties) {
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
SocketOptions options = new SocketOptions(); SocketOptions options = new SocketOptions();
map.from(this.properties::getConnectTimeout).whenNonNull() map.from(properties::getConnectTimeout).whenNonNull().asInt(Duration::toMillis)
.asInt(Duration::toMillis).to(options::setConnectTimeoutMillis); .to(options::setConnectTimeoutMillis);
map.from(this.properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setReadTimeoutMillis); .to(options::setReadTimeoutMillis);
return options; return options;
} }
private PoolingOptions getPoolingOptions() { private PoolingOptions getPoolingOptions(CassandraProperties properties) {
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
CassandraProperties.Pool properties = this.properties.getPool(); CassandraProperties.Pool poolProperties = properties.getPool();
PoolingOptions options = new PoolingOptions(); PoolingOptions options = new PoolingOptions();
map.from(properties::getIdleTimeout).whenNonNull().asInt(Duration::getSeconds) map.from(poolProperties::getIdleTimeout).whenNonNull().asInt(Duration::getSeconds)
.to(options::setIdleTimeoutSeconds); .to(options::setIdleTimeoutSeconds);
map.from(properties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis) map.from(poolProperties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setPoolTimeoutMillis); .to(options::setPoolTimeoutMillis);
map.from(properties::getHeartbeatInterval).whenNonNull() map.from(poolProperties::getHeartbeatInterval).whenNonNull()
.asInt(Duration::getSeconds).to(options::setHeartbeatIntervalSeconds); .asInt(Duration::getSeconds).to(options::setHeartbeatIntervalSeconds);
map.from(properties::getMaxQueueSize).to(options::setMaxQueueSize); map.from(poolProperties::getMaxQueueSize).to(options::setMaxQueueSize);
return options; return options;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -63,31 +63,24 @@ import org.springframework.data.cassandra.core.mapping.SimpleUserTypeResolver;
@AutoConfigureAfter(CassandraAutoConfiguration.class) @AutoConfigureAfter(CassandraAutoConfiguration.class)
public class CassandraDataAutoConfiguration { public class CassandraDataAutoConfiguration {
private final BeanFactory beanFactory;
private final CassandraProperties properties; private final CassandraProperties properties;
private final Cluster cluster; private final Cluster cluster;
private final Environment environment;
public CassandraDataAutoConfiguration(BeanFactory beanFactory, public CassandraDataAutoConfiguration(BeanFactory beanFactory,
CassandraProperties properties, Cluster cluster, Environment environment) { CassandraProperties properties, Cluster cluster, Environment environment) {
this.beanFactory = beanFactory;
this.properties = properties; this.properties = properties;
this.cluster = cluster; this.cluster = cluster;
this.environment = environment;
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public CassandraMappingContext cassandraMapping( public CassandraMappingContext cassandraMapping(BeanFactory beanFactory,
CassandraCustomConversions conversions) throws ClassNotFoundException { CassandraCustomConversions conversions) throws ClassNotFoundException {
CassandraMappingContext context = new CassandraMappingContext(); CassandraMappingContext context = new CassandraMappingContext();
List<String> packages = EntityScanPackages.get(this.beanFactory) List<String> packages = EntityScanPackages.get(beanFactory).getPackageNames();
.getPackageNames(); if (packages.isEmpty() && AutoConfigurationPackages.has(beanFactory)) {
if (packages.isEmpty() && AutoConfigurationPackages.has(this.beanFactory)) { packages = AutoConfigurationPackages.get(beanFactory);
packages = AutoConfigurationPackages.get(this.beanFactory);
} }
if (!packages.isEmpty()) { if (!packages.isEmpty()) {
context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages)); context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages));
@ -113,13 +106,13 @@ public class CassandraDataAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(Session.class) @ConditionalOnMissingBean(Session.class)
public CassandraSessionFactoryBean cassandraSession(CassandraConverter converter) public CassandraSessionFactoryBean cassandraSession(Environment environment,
throws Exception { CassandraConverter converter) throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean(); CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(this.cluster); session.setCluster(this.cluster);
session.setConverter(converter); session.setConverter(converter);
session.setKeyspaceName(this.properties.getKeyspaceName()); session.setKeyspaceName(this.properties.getKeyspaceName());
Binder binder = Binder.get(this.environment); Binder binder = Binder.get(environment);
binder.bind("spring.data.cassandra.schema-action", SchemaAction.class) binder.bind("spring.data.cassandra.schema-action", SchemaAction.class)
.ifBound(session::setSchemaAction); .ifBound(session::setSchemaAction);
return session; return session;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -38,24 +38,15 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@Configuration @Configuration
class MongoDataConfiguration { class MongoDataConfiguration {
private final ApplicationContext applicationContext;
private final MongoProperties properties;
MongoDataConfiguration(ApplicationContext applicationContext,
MongoProperties properties) {
this.applicationContext = applicationContext;
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions) public MongoMappingContext mongoMappingContext(ApplicationContext applicationContext,
MongoProperties properties, MongoCustomConversions conversions)
throws ClassNotFoundException { throws ClassNotFoundException {
MongoMappingContext context = new MongoMappingContext(); MongoMappingContext context = new MongoMappingContext();
context.setInitialEntitySet(new EntityScanner(this.applicationContext) context.setInitialEntitySet(new EntityScanner(applicationContext)
.scan(Document.class, Persistent.class)); .scan(Document.class, Persistent.class));
Class<?> strategyClass = this.properties.getFieldNamingStrategy(); Class<?> strategyClass = properties.getFieldNamingStrategy();
if (strategyClass != null) { if (strategyClass != null) {
context.setFieldNamingStrategy( context.setFieldNamingStrategy(
(FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass)); (FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -59,17 +59,11 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@AutoConfigureAfter(MongoReactiveAutoConfiguration.class) @AutoConfigureAfter(MongoReactiveAutoConfiguration.class)
public class MongoReactiveDataAutoConfiguration { public class MongoReactiveDataAutoConfiguration {
private final MongoProperties properties;
public MongoReactiveDataAutoConfiguration(MongoProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean(ReactiveMongoDatabaseFactory.class) @ConditionalOnMissingBean(ReactiveMongoDatabaseFactory.class)
public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory( public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory(
MongoClient mongo) { MongoProperties properties, MongoClient mongo) {
String database = this.properties.getMongoClientDatabase(); String database = properties.getMongoClientDatabase();
return new SimpleReactiveMongoDatabaseFactory(mongo, database); return new SimpleReactiveMongoDatabaseFactory(mongo, database);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,27 +47,24 @@ import org.springframework.util.StringUtils;
@ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class }) @ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class })
class JedisConnectionConfiguration extends RedisConnectionConfiguration { class JedisConnectionConfiguration extends RedisConnectionConfiguration {
private final RedisProperties properties;
private final ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers;
JedisConnectionConfiguration(RedisProperties properties, JedisConnectionConfiguration(RedisProperties properties,
ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration, ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration,
ObjectProvider<RedisClusterConfiguration> clusterConfiguration, ObjectProvider<RedisClusterConfiguration> clusterConfiguration) {
ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
super(properties, sentinelConfiguration, clusterConfiguration); super(properties, sentinelConfiguration, clusterConfiguration);
this.properties = properties;
this.builderCustomizers = builderCustomizers;
} }
@Bean @Bean
@ConditionalOnMissingBean(RedisConnectionFactory.class) @ConditionalOnMissingBean(RedisConnectionFactory.class)
public JedisConnectionFactory redisConnectionFactory() throws UnknownHostException { public JedisConnectionFactory redisConnectionFactory(
return createJedisConnectionFactory(); ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers)
throws UnknownHostException {
return createJedisConnectionFactory(builderCustomizers);
} }
private JedisConnectionFactory createJedisConnectionFactory() { private JedisConnectionFactory createJedisConnectionFactory(
JedisClientConfiguration clientConfiguration = getJedisClientConfiguration(); ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
JedisClientConfiguration clientConfiguration = getJedisClientConfiguration(
builderCustomizers);
if (getSentinelConfig() != null) { if (getSentinelConfig() != null) {
return new JedisConnectionFactory(getSentinelConfig(), clientConfiguration); return new JedisConnectionFactory(getSentinelConfig(), clientConfiguration);
} }
@ -78,27 +75,29 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration {
return new JedisConnectionFactory(getStandaloneConfig(), clientConfiguration); return new JedisConnectionFactory(getStandaloneConfig(), clientConfiguration);
} }
private JedisClientConfiguration getJedisClientConfiguration() { private JedisClientConfiguration getJedisClientConfiguration(
ObjectProvider<JedisClientConfigurationBuilderCustomizer> builderCustomizers) {
JedisClientConfigurationBuilder builder = applyProperties( JedisClientConfigurationBuilder builder = applyProperties(
JedisClientConfiguration.builder()); JedisClientConfiguration.builder());
RedisProperties.Pool pool = this.properties.getJedis().getPool(); RedisProperties.Pool pool = getProperties().getJedis().getPool();
if (pool != null) { if (pool != null) {
applyPooling(pool, builder); applyPooling(pool, builder);
} }
if (StringUtils.hasText(this.properties.getUrl())) { if (StringUtils.hasText(getProperties().getUrl())) {
customizeConfigurationFromUrl(builder); customizeConfigurationFromUrl(builder);
} }
customize(builder); builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
return builder.build(); return builder.build();
} }
private JedisClientConfigurationBuilder applyProperties( private JedisClientConfigurationBuilder applyProperties(
JedisClientConfigurationBuilder builder) { JedisClientConfigurationBuilder builder) {
if (this.properties.isSsl()) { if (getProperties().isSsl()) {
builder.useSsl(); builder.useSsl();
} }
if (this.properties.getTimeout() != null) { if (getProperties().getTimeout() != null) {
Duration timeout = this.properties.getTimeout(); Duration timeout = getProperties().getTimeout();
builder.readTimeout(timeout).connectTimeout(timeout); builder.readTimeout(timeout).connectTimeout(timeout);
} }
return builder; return builder;
@ -122,16 +121,10 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration {
private void customizeConfigurationFromUrl( private void customizeConfigurationFromUrl(
JedisClientConfiguration.JedisClientConfigurationBuilder builder) { JedisClientConfiguration.JedisClientConfigurationBuilder builder) {
ConnectionInfo connectionInfo = parseUrl(this.properties.getUrl()); ConnectionInfo connectionInfo = parseUrl(getProperties().getUrl());
if (connectionInfo.isUseSsl()) { if (connectionInfo.isUseSsl()) {
builder.useSsl(); builder.useSsl();
} }
} }
private void customize(
JedisClientConfiguration.JedisClientConfigurationBuilder builder) {
this.builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -48,17 +48,10 @@ import org.springframework.util.StringUtils;
@ConditionalOnClass(RedisClient.class) @ConditionalOnClass(RedisClient.class)
class LettuceConnectionConfiguration extends RedisConnectionConfiguration { class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
private final RedisProperties properties;
private final ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers;
LettuceConnectionConfiguration(RedisProperties properties, LettuceConnectionConfiguration(RedisProperties properties,
ObjectProvider<RedisSentinelConfiguration> sentinelConfigurationProvider, ObjectProvider<RedisSentinelConfiguration> sentinelConfigurationProvider,
ObjectProvider<RedisClusterConfiguration> clusterConfigurationProvider, ObjectProvider<RedisClusterConfiguration> clusterConfigurationProvider) {
ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers) {
super(properties, sentinelConfigurationProvider, clusterConfigurationProvider); super(properties, sentinelConfigurationProvider, clusterConfigurationProvider);
this.properties = properties;
this.builderCustomizers = builderCustomizers;
} }
@Bean(destroyMethod = "shutdown") @Bean(destroyMethod = "shutdown")
@ -70,9 +63,11 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(RedisConnectionFactory.class) @ConditionalOnMissingBean(RedisConnectionFactory.class)
public LettuceConnectionFactory redisConnectionFactory( public LettuceConnectionFactory redisConnectionFactory(
ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
ClientResources clientResources) throws UnknownHostException { ClientResources clientResources) throws UnknownHostException {
LettuceClientConfiguration clientConfig = getLettuceClientConfiguration( LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(
clientResources, this.properties.getLettuce().getPool()); builderCustomizers, clientResources,
getProperties().getLettuce().getPool());
return createLettuceConnectionFactory(clientConfig); return createLettuceConnectionFactory(clientConfig);
} }
@ -89,14 +84,16 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
} }
private LettuceClientConfiguration getLettuceClientConfiguration( private LettuceClientConfiguration getLettuceClientConfiguration(
ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
ClientResources clientResources, Pool pool) { ClientResources clientResources, Pool pool) {
LettuceClientConfigurationBuilder builder = createBuilder(pool); LettuceClientConfigurationBuilder builder = createBuilder(pool);
applyProperties(builder); applyProperties(builder);
if (StringUtils.hasText(this.properties.getUrl())) { if (StringUtils.hasText(getProperties().getUrl())) {
customizeConfigurationFromUrl(builder); customizeConfigurationFromUrl(builder);
} }
builder.clientResources(clientResources); builder.clientResources(clientResources);
customize(builder); builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
return builder.build(); return builder.build();
} }
@ -109,18 +106,18 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
private LettuceClientConfigurationBuilder applyProperties( private LettuceClientConfigurationBuilder applyProperties(
LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) {
if (this.properties.isSsl()) { if (getProperties().isSsl()) {
builder.useSsl(); builder.useSsl();
} }
if (this.properties.getTimeout() != null) { if (getProperties().getTimeout() != null) {
builder.commandTimeout(this.properties.getTimeout()); builder.commandTimeout(getProperties().getTimeout());
} }
if (this.properties.getLettuce() != null) { if (getProperties().getLettuce() != null) {
RedisProperties.Lettuce lettuce = this.properties.getLettuce(); RedisProperties.Lettuce lettuce = getProperties().getLettuce();
if (lettuce.getShutdownTimeout() != null if (lettuce.getShutdownTimeout() != null
&& !lettuce.getShutdownTimeout().isZero()) { && !lettuce.getShutdownTimeout().isZero()) {
builder.shutdownTimeout( builder.shutdownTimeout(
this.properties.getLettuce().getShutdownTimeout()); getProperties().getLettuce().getShutdownTimeout());
} }
} }
return builder; return builder;
@ -128,18 +125,12 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
private void customizeConfigurationFromUrl( private void customizeConfigurationFromUrl(
LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) {
ConnectionInfo connectionInfo = parseUrl(this.properties.getUrl()); ConnectionInfo connectionInfo = parseUrl(getProperties().getUrl());
if (connectionInfo.isUseSsl()) { if (connectionInfo.isUseSsl()) {
builder.useSsl(); builder.useSsl();
} }
} }
private void customize(
LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) {
this.builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
}
/** /**
* Inner class to allow optional commons-pool2 dependency. * Inner class to allow optional commons-pool2 dependency.
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -111,6 +111,10 @@ abstract class RedisConnectionConfiguration {
return config; return config;
} }
protected final RedisProperties getProperties() {
return this.properties;
}
private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) { private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<>(); List<RedisNode> nodes = new ArrayList<>();
for (String node : sentinel.getNodes()) { for (String node : sentinel.getNodes()) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,51 +49,38 @@ import org.springframework.util.Assert;
@AutoConfigureAfter(GsonAutoConfiguration.class) @AutoConfigureAfter(GsonAutoConfiguration.class)
public class JestAutoConfiguration { public class JestAutoConfiguration {
private final JestProperties properties;
private final ObjectProvider<Gson> gsonProvider;
private final ObjectProvider<HttpClientConfigBuilderCustomizer> builderCustomizers;
public JestAutoConfiguration(JestProperties properties, ObjectProvider<Gson> gson,
ObjectProvider<HttpClientConfigBuilderCustomizer> builderCustomizers) {
this.properties = properties;
this.gsonProvider = gson;
this.builderCustomizers = builderCustomizers;
}
@Bean(destroyMethod = "shutdownClient") @Bean(destroyMethod = "shutdownClient")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public JestClient jestClient() { public JestClient jestClient(JestProperties properties, ObjectProvider<Gson> gson,
ObjectProvider<HttpClientConfigBuilderCustomizer> builderCustomizers) {
JestClientFactory factory = new JestClientFactory(); JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(createHttpClientConfig()); factory.setHttpClientConfig(
createHttpClientConfig(properties, gson, builderCustomizers));
return factory.getObject(); return factory.getObject();
} }
protected HttpClientConfig createHttpClientConfig() { protected HttpClientConfig createHttpClientConfig(JestProperties properties,
ObjectProvider<Gson> gson,
ObjectProvider<HttpClientConfigBuilderCustomizer> builderCustomizers) {
HttpClientConfig.Builder builder = new HttpClientConfig.Builder( HttpClientConfig.Builder builder = new HttpClientConfig.Builder(
this.properties.getUris()); properties.getUris());
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
map.from(this.properties::getUsername).whenHasText().to((username) -> builder map.from(properties::getUsername).whenHasText().to((username) -> builder
.defaultCredentials(username, this.properties.getPassword())); .defaultCredentials(username, properties.getPassword()));
Proxy proxy = this.properties.getProxy(); Proxy proxy = properties.getProxy();
map.from(proxy::getHost).whenHasText().to((host) -> { map.from(proxy::getHost).whenHasText().to((host) -> {
Assert.notNull(proxy.getPort(), "Proxy port must not be null"); Assert.notNull(proxy.getPort(), "Proxy port must not be null");
builder.proxy(new HttpHost(host, proxy.getPort())); builder.proxy(new HttpHost(host, proxy.getPort()));
}); });
map.from(this.gsonProvider::getIfUnique).whenNonNull().to(builder::gson); map.from(gson::getIfUnique).whenNonNull().to(builder::gson);
map.from(this.properties::isMultiThreaded).to(builder::multiThreaded); map.from(properties::isMultiThreaded).to(builder::multiThreaded);
map.from(this.properties::getConnectionTimeout).whenNonNull() map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis)
.asInt(Duration::toMillis).to(builder::connTimeout); .to(builder::connTimeout);
map.from(this.properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis)
.to(builder::readTimeout); .to(builder::readTimeout);
customize(builder); builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
return builder.build(); return builder.build();
} }
private void customize(HttpClientConfig.Builder builder) {
this.builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -46,16 +46,6 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties(RestClientProperties.class) @EnableConfigurationProperties(RestClientProperties.class)
public class RestClientAutoConfiguration { public class RestClientAutoConfiguration {
private final RestClientProperties properties;
private final ObjectProvider<RestClientBuilderCustomizer> builderCustomizers;
public RestClientAutoConfiguration(RestClientProperties properties,
ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {
this.properties = properties;
this.builderCustomizers = builderCustomizers;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public RestClient restClient(RestClientBuilder builder) { public RestClient restClient(RestClientBuilder builder) {
@ -64,20 +54,21 @@ public class RestClientAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public RestClientBuilder restClientBuilder() { public RestClientBuilder restClientBuilder(RestClientProperties properties,
HttpHost[] hosts = this.properties.getUris().stream().map(HttpHost::create) ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {
HttpHost[] hosts = properties.getUris().stream().map(HttpHost::create)
.toArray(HttpHost[]::new); .toArray(HttpHost[]::new);
RestClientBuilder builder = RestClient.builder(hosts); RestClientBuilder builder = RestClient.builder(hosts);
PropertyMapper map = PropertyMapper.get(); PropertyMapper map = PropertyMapper.get();
map.from(this.properties::getUsername).whenHasText().to((username) -> { map.from(properties::getUsername).whenHasText().to((username) -> {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials( Credentials credentials = new UsernamePasswordCredentials(
this.properties.getUsername(), this.properties.getPassword()); properties.getUsername(), properties.getPassword());
credentialsProvider.setCredentials(AuthScope.ANY, credentials); credentialsProvider.setCredentials(AuthScope.ANY, credentials);
builder.setHttpClientConfigCallback((httpClientBuilder) -> httpClientBuilder builder.setHttpClientConfigCallback((httpClientBuilder) -> httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider)); .setDefaultCredentialsProvider(credentialsProvider));
}); });
this.builderCustomizers.orderedStream() builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder)); .forEach((customizer) -> customizer.customize(builder));
return builder; return builder;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -104,25 +104,8 @@ public class FlywayAutoConfiguration {
@EnableConfigurationProperties({ DataSourceProperties.class, FlywayProperties.class }) @EnableConfigurationProperties({ DataSourceProperties.class, FlywayProperties.class })
public static class FlywayConfiguration { public static class FlywayConfiguration {
private final FlywayProperties properties; @Bean
public Flyway flyway(FlywayProperties properties,
private final DataSourceProperties dataSourceProperties;
private final ResourceLoader resourceLoader;
private final DataSource dataSource;
private final DataSource flywayDataSource;
private final FlywayMigrationStrategy migrationStrategy;
private final List<FlywayConfigurationCustomizer> configurationCustomizers;
private final List<Callback> callbacks;
private final List<FlywayCallback> flywayCallbacks;
public FlywayConfiguration(FlywayProperties properties,
DataSourceProperties dataSourceProperties, ResourceLoader resourceLoader, DataSourceProperties dataSourceProperties, ResourceLoader resourceLoader,
ObjectProvider<DataSource> dataSource, ObjectProvider<DataSource> dataSource,
@FlywayDataSource ObjectProvider<DataSource> flywayDataSource, @FlywayDataSource ObjectProvider<DataSource> flywayDataSource,
@ -130,141 +113,135 @@ public class FlywayAutoConfiguration {
ObjectProvider<FlywayConfigurationCustomizer> fluentConfigurationCustomizers, ObjectProvider<FlywayConfigurationCustomizer> fluentConfigurationCustomizers,
ObjectProvider<Callback> callbacks, ObjectProvider<Callback> callbacks,
ObjectProvider<FlywayCallback> flywayCallbacks) { ObjectProvider<FlywayCallback> flywayCallbacks) {
this.properties = properties;
this.dataSourceProperties = dataSourceProperties;
this.resourceLoader = resourceLoader;
this.dataSource = dataSource.getIfUnique();
this.flywayDataSource = flywayDataSource.getIfAvailable();
this.migrationStrategy = migrationStrategy.getIfAvailable();
this.configurationCustomizers = fluentConfigurationCustomizers.orderedStream()
.collect(Collectors.toList());
this.callbacks = callbacks.orderedStream().collect(Collectors.toList());
this.flywayCallbacks = flywayCallbacks.orderedStream()
.collect(Collectors.toList());
}
@Bean
public Flyway flyway() {
FluentConfiguration configuration = new FluentConfiguration(); FluentConfiguration configuration = new FluentConfiguration();
DataSource dataSource = configureDataSource(configuration); DataSource dataSourceToMigrate = configureDataSource(configuration,
checkLocationExists(dataSource); properties, dataSourceProperties, flywayDataSource.getIfAvailable(),
configureProperties(configuration); dataSource.getIfAvailable());
configureCallbacks(configuration); checkLocationExists(dataSourceToMigrate, properties, resourceLoader);
this.configurationCustomizers configureProperties(configuration, properties);
List<Callback> orderedCallbacks = callbacks.orderedStream()
.collect(Collectors.toList());
configureCallbacks(configuration, orderedCallbacks);
fluentConfigurationCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(configuration)); .forEach((customizer) -> customizer.customize(configuration));
Flyway flyway = configuration.load(); Flyway flyway = configuration.load();
configureFlywayCallbacks(flyway); List<FlywayCallback> orderedFlywayCallbacks = flywayCallbacks.orderedStream()
.collect(Collectors.toList());
configureFlywayCallbacks(flyway, orderedCallbacks, orderedFlywayCallbacks);
return flyway; return flyway;
} }
private DataSource configureDataSource(FluentConfiguration configuration) { private DataSource configureDataSource(FluentConfiguration configuration,
if (this.properties.isCreateDataSource()) { FlywayProperties properties, DataSourceProperties dataSourceProperties,
String url = getProperty(this.properties::getUrl, DataSource flywayDataSource, DataSource dataSource) {
this.dataSourceProperties::getUrl); if (properties.isCreateDataSource()) {
String user = getProperty(this.properties::getUser, String url = getProperty(properties::getUrl,
this.dataSourceProperties::getUsername); dataSourceProperties::getUrl);
String password = getProperty(this.properties::getPassword, String user = getProperty(properties::getUser,
this.dataSourceProperties::getPassword); dataSourceProperties::getUsername);
String password = getProperty(properties::getPassword,
dataSourceProperties::getPassword);
configuration.dataSource(url, user, password); configuration.dataSource(url, user, password);
if (!CollectionUtils.isEmpty(this.properties.getInitSqls())) { if (!CollectionUtils.isEmpty(properties.getInitSqls())) {
String initSql = StringUtils.collectionToDelimitedString( String initSql = StringUtils
this.properties.getInitSqls(), "\n"); .collectionToDelimitedString(properties.getInitSqls(), "\n");
configuration.initSql(initSql); configuration.initSql(initSql);
} }
} }
else if (this.flywayDataSource != null) { else if (flywayDataSource != null) {
configuration.dataSource(this.flywayDataSource); configuration.dataSource(flywayDataSource);
} }
else { else {
configuration.dataSource(this.dataSource); configuration.dataSource(dataSource);
} }
return configuration.getDataSource(); return configuration.getDataSource();
} }
private void checkLocationExists(DataSource dataSource) { private void checkLocationExists(DataSource dataSource,
if (this.properties.isCheckLocation()) { FlywayProperties properties, ResourceLoader resourceLoader) {
if (properties.isCheckLocation()) {
String[] locations = new LocationResolver(dataSource) String[] locations = new LocationResolver(dataSource)
.resolveLocations(this.properties.getLocations()); .resolveLocations(properties.getLocations());
Assert.state(locations.length != 0, Assert.state(locations.length != 0,
"Migration script locations not configured"); "Migration script locations not configured");
boolean exists = hasAtLeastOneLocation(locations); boolean exists = hasAtLeastOneLocation(resourceLoader, locations);
Assert.state(exists, () -> "Cannot find migrations location in: " Assert.state(exists, () -> "Cannot find migrations location in: "
+ Arrays.asList(locations) + Arrays.asList(locations)
+ " (please add migrations or check your Flyway configuration)"); + " (please add migrations or check your Flyway configuration)");
} }
} }
private void configureProperties(FluentConfiguration configuration) { private void configureProperties(FluentConfiguration configuration,
FlywayProperties properties) {
PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
String[] locations = new LocationResolver(configuration.getDataSource()) String[] locations = new LocationResolver(configuration.getDataSource())
.resolveLocations(this.properties.getLocations()); .resolveLocations(properties.getLocations());
map.from(locations).to(configuration::locations); map.from(locations).to(configuration::locations);
map.from(this.properties.getEncoding()).to(configuration::encoding); map.from(properties.getEncoding()).to(configuration::encoding);
map.from(this.properties.getConnectRetries()) map.from(properties.getConnectRetries()).to(configuration::connectRetries);
.to(configuration::connectRetries); map.from(properties.getSchemas()).as(StringUtils::toStringArray)
map.from(this.properties.getSchemas()).as(StringUtils::toStringArray)
.to(configuration::schemas); .to(configuration::schemas);
map.from(this.properties.getTable()).to(configuration::table); map.from(properties.getTable()).to(configuration::table);
map.from(this.properties.getBaselineDescription()) map.from(properties.getBaselineDescription())
.to(configuration::baselineDescription); .to(configuration::baselineDescription);
map.from(this.properties.getBaselineVersion()) map.from(properties.getBaselineVersion()).to(configuration::baselineVersion);
.to(configuration::baselineVersion); map.from(properties.getInstalledBy()).to(configuration::installedBy);
map.from(this.properties.getInstalledBy()).to(configuration::installedBy); map.from(properties.getPlaceholders()).to(configuration::placeholders);
map.from(this.properties.getPlaceholders()).to(configuration::placeholders); map.from(properties.getPlaceholderPrefix())
map.from(this.properties.getPlaceholderPrefix())
.to(configuration::placeholderPrefix); .to(configuration::placeholderPrefix);
map.from(this.properties.getPlaceholderSuffix()) map.from(properties.getPlaceholderSuffix())
.to(configuration::placeholderSuffix); .to(configuration::placeholderSuffix);
map.from(this.properties.isPlaceholderReplacement()) map.from(properties.isPlaceholderReplacement())
.to(configuration::placeholderReplacement); .to(configuration::placeholderReplacement);
map.from(this.properties.getSqlMigrationPrefix()) map.from(properties.getSqlMigrationPrefix())
.to(configuration::sqlMigrationPrefix); .to(configuration::sqlMigrationPrefix);
map.from(this.properties.getSqlMigrationSuffixes()) map.from(properties.getSqlMigrationSuffixes()).as(StringUtils::toStringArray)
.as(StringUtils::toStringArray)
.to(configuration::sqlMigrationSuffixes); .to(configuration::sqlMigrationSuffixes);
map.from(this.properties.getSqlMigrationSeparator()) map.from(properties.getSqlMigrationSeparator())
.to(configuration::sqlMigrationSeparator); .to(configuration::sqlMigrationSeparator);
map.from(this.properties.getRepeatableSqlMigrationPrefix()) map.from(properties.getRepeatableSqlMigrationPrefix())
.to(configuration::repeatableSqlMigrationPrefix); .to(configuration::repeatableSqlMigrationPrefix);
map.from(this.properties.getTarget()).to(configuration::target); map.from(properties.getTarget()).to(configuration::target);
map.from(this.properties.isBaselineOnMigrate()) map.from(properties.isBaselineOnMigrate())
.to(configuration::baselineOnMigrate); .to(configuration::baselineOnMigrate);
map.from(this.properties.isCleanDisabled()).to(configuration::cleanDisabled); map.from(properties.isCleanDisabled()).to(configuration::cleanDisabled);
map.from(this.properties.isCleanOnValidationError()) map.from(properties.isCleanOnValidationError())
.to(configuration::cleanOnValidationError); .to(configuration::cleanOnValidationError);
map.from(this.properties.isGroup()).to(configuration::group); map.from(properties.isGroup()).to(configuration::group);
map.from(this.properties.isIgnoreMissingMigrations()) map.from(properties.isIgnoreMissingMigrations())
.to(configuration::ignoreMissingMigrations); .to(configuration::ignoreMissingMigrations);
map.from(this.properties.isIgnoreIgnoredMigrations()) map.from(properties.isIgnoreIgnoredMigrations())
.to(configuration::ignoreIgnoredMigrations); .to(configuration::ignoreIgnoredMigrations);
map.from(this.properties.isIgnorePendingMigrations()) map.from(properties.isIgnorePendingMigrations())
.to(configuration::ignorePendingMigrations); .to(configuration::ignorePendingMigrations);
map.from(this.properties.isIgnoreFutureMigrations()) map.from(properties.isIgnoreFutureMigrations())
.to(configuration::ignoreFutureMigrations); .to(configuration::ignoreFutureMigrations);
map.from(this.properties.isMixed()).to(configuration::mixed); map.from(properties.isMixed()).to(configuration::mixed);
map.from(this.properties.isOutOfOrder()).to(configuration::outOfOrder); map.from(properties.isOutOfOrder()).to(configuration::outOfOrder);
map.from(this.properties.isSkipDefaultCallbacks()) map.from(properties.isSkipDefaultCallbacks())
.to(configuration::skipDefaultCallbacks); .to(configuration::skipDefaultCallbacks);
map.from(this.properties.isSkipDefaultResolvers()) map.from(properties.isSkipDefaultResolvers())
.to(configuration::skipDefaultResolvers); .to(configuration::skipDefaultResolvers);
map.from(this.properties.isValidateOnMigrate()) map.from(properties.isValidateOnMigrate())
.to(configuration::validateOnMigrate); .to(configuration::validateOnMigrate);
} }
private void configureCallbacks(FluentConfiguration configuration) { private void configureCallbacks(FluentConfiguration configuration,
if (!this.callbacks.isEmpty()) { List<Callback> callbacks) {
configuration.callbacks(this.callbacks.toArray(new Callback[0])); if (!callbacks.isEmpty()) {
configuration.callbacks(callbacks.toArray(new Callback[0]));
} }
} }
private void configureFlywayCallbacks(Flyway flyway) { private void configureFlywayCallbacks(Flyway flyway, List<Callback> callbacks,
if (!this.flywayCallbacks.isEmpty()) { List<FlywayCallback> flywayCallbacks) {
if (!this.callbacks.isEmpty()) { if (!flywayCallbacks.isEmpty()) {
if (!callbacks.isEmpty()) {
throw new IllegalStateException( throw new IllegalStateException(
"Found a mixture of Callback and FlywayCallback beans." "Found a mixture of Callback and FlywayCallback beans."
+ " One type must be used exclusively."); + " One type must be used exclusively.");
} }
flyway.setCallbacks(this.flywayCallbacks.toArray(new FlywayCallback[0])); flyway.setCallbacks(flywayCallbacks.toArray(new FlywayCallback[0]));
} }
} }
@ -274,9 +251,10 @@ public class FlywayAutoConfiguration {
return (value != null) ? value : defaultValue.get(); return (value != null) ? value : defaultValue.get();
} }
private boolean hasAtLeastOneLocation(String... locations) { private boolean hasAtLeastOneLocation(ResourceLoader resourceLoader,
String... locations) {
for (String location : locations) { for (String location : locations) {
if (this.resourceLoader.getResource(normalizePrefix(location)).exists()) { if (resourceLoader.getResource(normalizePrefix(location)).exists()) {
return true; return true;
} }
} }
@ -289,8 +267,10 @@ public class FlywayAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public FlywayMigrationInitializer flywayInitializer(Flyway flyway) { public FlywayMigrationInitializer flywayInitializer(Flyway flyway,
return new FlywayMigrationInitializer(flyway, this.migrationStrategy); ObjectProvider<FlywayMigrationStrategy> migrationStrategy) {
return new FlywayMigrationInitializer(flyway,
migrationStrategy.getIfAvailable());
} }
/** /**

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -74,14 +74,11 @@ public class GroovyTemplateAutoConfiguration {
private final GroovyTemplateProperties properties; private final GroovyTemplateProperties properties;
private final MarkupTemplateEngine templateEngine;
public GroovyMarkupConfiguration(ApplicationContext applicationContext, public GroovyMarkupConfiguration(ApplicationContext applicationContext,
GroovyTemplateProperties properties, GroovyTemplateProperties properties,
ObjectProvider<MarkupTemplateEngine> templateEngine) { ObjectProvider<MarkupTemplateEngine> templateEngine) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.properties = properties; this.properties = properties;
this.templateEngine = templateEngine.getIfAvailable();
} }
@PostConstruct @PostConstruct
@ -124,13 +121,12 @@ public class GroovyTemplateAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(GroovyMarkupConfig.class) @ConditionalOnMissingBean(GroovyMarkupConfig.class)
@ConfigurationProperties(prefix = "spring.groovy.template.configuration") @ConfigurationProperties(prefix = "spring.groovy.template.configuration")
public GroovyMarkupConfigurer groovyMarkupConfigurer() { public GroovyMarkupConfigurer groovyMarkupConfigurer(
ObjectProvider<MarkupTemplateEngine> templateEngine) {
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
configurer.setResourceLoaderPath(this.properties.getResourceLoaderPath()); configurer.setResourceLoaderPath(this.properties.getResourceLoaderPath());
configurer.setCacheTemplates(this.properties.isCache()); configurer.setCacheTemplates(this.properties.isCache());
if (this.templateEngine != null) { templateEngine.ifAvailable(configurer::setTemplateEngine);
configurer.setTemplateEngine(this.templateEngine);
}
return configurer; return configurer;
} }
@ -143,17 +139,12 @@ public class GroovyTemplateAutoConfiguration {
@ConditionalOnProperty(name = "spring.groovy.template.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "spring.groovy.template.enabled", matchIfMissing = true)
public static class GroovyWebConfiguration { public static class GroovyWebConfiguration {
private final GroovyTemplateProperties properties;
public GroovyWebConfiguration(GroovyTemplateProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "groovyMarkupViewResolver") @ConditionalOnMissingBean(name = "groovyMarkupViewResolver")
public GroovyMarkupViewResolver groovyMarkupViewResolver() { public GroovyMarkupViewResolver groovyMarkupViewResolver(
GroovyTemplateProperties properties) {
GroovyMarkupViewResolver resolver = new GroovyMarkupViewResolver(); GroovyMarkupViewResolver resolver = new GroovyMarkupViewResolver();
this.properties.applyToMvcViewResolver(resolver); properties.applyToMvcViewResolver(resolver);
return resolver; return resolver;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,19 +43,13 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties(H2ConsoleProperties.class) @EnableConfigurationProperties(H2ConsoleProperties.class)
public class H2ConsoleAutoConfiguration { public class H2ConsoleAutoConfiguration {
private final H2ConsoleProperties properties;
public H2ConsoleAutoConfiguration(H2ConsoleProperties properties) {
this.properties = properties;
}
@Bean @Bean
public ServletRegistrationBean<WebServlet> h2Console() { public ServletRegistrationBean<WebServlet> h2Console(H2ConsoleProperties properties) {
String path = this.properties.getPath(); String path = properties.getPath();
String urlMapping = path + (path.endsWith("/") ? "*" : "/*"); String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
ServletRegistrationBean<WebServlet> registration = new ServletRegistrationBean<>( ServletRegistrationBean<WebServlet> registration = new ServletRegistrationBean<>(
new WebServlet(), urlMapping); new WebServlet(), urlMapping);
H2ConsoleProperties.Settings settings = this.properties.getSettings(); H2ConsoleProperties.Settings settings = properties.getSettings();
if (settings.isTrace()) { if (settings.isTrace()) {
registration.addInitParameter("trace", ""); registration.addInitParameter("trace", "");
} }

View File

@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.http; package org.springframework.boot.autoconfigure.http;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
@ -64,17 +63,12 @@ public class HttpMessageConvertersAutoConfiguration {
static final String PREFERRED_MAPPER_PROPERTY = "spring.http.converters.preferred-json-mapper"; static final String PREFERRED_MAPPER_PROPERTY = "spring.http.converters.preferred-json-mapper";
private final List<HttpMessageConverter<?>> converters;
public HttpMessageConvertersAutoConfiguration(
ObjectProvider<HttpMessageConverter<?>> convertersProvider) {
this.converters = convertersProvider.orderedStream().collect(Collectors.toList());
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public HttpMessageConverters messageConverters() { public HttpMessageConverters messageConverters(
return new HttpMessageConverters(this.converters); ObjectProvider<HttpMessageConverter<?>> converters) {
return new HttpMessageConverters(
converters.orderedStream().collect(Collectors.toList()));
} }
@Configuration @Configuration
@ -82,17 +76,12 @@ public class HttpMessageConvertersAutoConfiguration {
@EnableConfigurationProperties(HttpProperties.class) @EnableConfigurationProperties(HttpProperties.class)
protected static class StringHttpMessageConverterConfiguration { protected static class StringHttpMessageConverterConfiguration {
private final HttpProperties.Encoding properties;
protected StringHttpMessageConverterConfiguration(HttpProperties httpProperties) {
this.properties = httpProperties.getEncoding();
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public StringHttpMessageConverter stringHttpMessageConverter() { public StringHttpMessageConverter stringHttpMessageConverter(
HttpProperties httpProperties) {
StringHttpMessageConverter converter = new StringHttpMessageConverter( StringHttpMessageConverter converter = new StringHttpMessageConverter(
this.properties.getCharset()); httpProperties.getEncoding().getCharset());
converter.setWriteAcceptCharset(false); converter.setWriteAcceptCharset(false);
return converter; return converter;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -46,16 +46,15 @@ public class InfluxDbAutoConfiguration {
private static final Log logger = LogFactory.getLog(InfluxDbAutoConfiguration.class); private static final Log logger = LogFactory.getLog(InfluxDbAutoConfiguration.class);
private final InfluxDbProperties properties; @Bean
@ConditionalOnMissingBean
private final OkHttpClient.Builder builder; @ConditionalOnProperty("spring.influx.url")
public InfluxDB influxDb(InfluxDbProperties properties,
public InfluxDbAutoConfiguration(InfluxDbProperties properties,
ObjectProvider<InfluxDbOkHttpClientBuilderProvider> builder, ObjectProvider<InfluxDbOkHttpClientBuilderProvider> builder,
ObjectProvider<OkHttpClient.Builder> deprecatedBuilder) { ObjectProvider<OkHttpClient.Builder> deprecatedBuilder) {
this.properties = properties; return new InfluxDBImpl(properties.getUrl(), properties.getUser(),
this.builder = determineBuilder(builder.getIfAvailable(), properties.getPassword(), determineBuilder(builder.getIfAvailable(),
deprecatedBuilder.getIfAvailable()); deprecatedBuilder.getIfAvailable()));
} }
@Deprecated @Deprecated
@ -75,12 +74,4 @@ public class InfluxDbAutoConfiguration {
return new OkHttpClient.Builder(); return new OkHttpClient.Builder();
} }
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty("spring.influx.url")
public InfluxDB influxDb() {
return new InfluxDBImpl(this.properties.getUrl(), this.properties.getUser(),
this.properties.getPassword(), this.builder);
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,9 +19,7 @@ package org.springframework.boot.autoconfigure.integration;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -32,7 +30,6 @@ import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration; import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
@ -81,34 +78,19 @@ public class IntegrationAutoConfiguration {
@ConditionalOnMissingBean(value = IntegrationMBeanExporter.class, search = SearchStrategy.CURRENT) @ConditionalOnMissingBean(value = IntegrationMBeanExporter.class, search = SearchStrategy.CURRENT)
@ConditionalOnBean(MBeanServer.class) @ConditionalOnBean(MBeanServer.class)
@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true)
protected static class IntegrationJmxConfiguration protected static class IntegrationJmxConfiguration {
implements EnvironmentAware, BeanFactoryAware {
private BeanFactory beanFactory;
private Environment environment;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Bean @Bean
public IntegrationMBeanExporter integrationMbeanExporter() { public IntegrationMBeanExporter integrationMbeanExporter(BeanFactory beanFactory,
Environment environment) {
IntegrationMBeanExporter exporter = new IntegrationMBeanExporter(); IntegrationMBeanExporter exporter = new IntegrationMBeanExporter();
String defaultDomain = this.environment String defaultDomain = environment.getProperty("spring.jmx.default-domain");
.getProperty("spring.jmx.default-domain");
if (StringUtils.hasLength(defaultDomain)) { if (StringUtils.hasLength(defaultDomain)) {
exporter.setDefaultDomain(defaultDomain); exporter.setDefaultDomain(defaultDomain);
} }
String serverBean = this.environment.getProperty("spring.jmx.server", String serverBean = environment.getProperty("spring.jmx.server",
"mbeanServer"); "mbeanServer");
exporter.setServer(this.beanFactory.getBean(serverBean, MBeanServer.class)); exporter.setServer(beanFactory.getBean(serverBean, MBeanServer.class));
return exporter; return exporter;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -116,16 +116,12 @@ public class JacksonAutoConfiguration {
private static final Log logger = LogFactory private static final Log logger = LogFactory
.getLog(JodaDateTimeJacksonConfiguration.class); .getLog(JodaDateTimeJacksonConfiguration.class);
private final JacksonProperties jacksonProperties;
JodaDateTimeJacksonConfiguration(JacksonProperties jacksonProperties) {
this.jacksonProperties = jacksonProperties;
}
@Bean @Bean
public SimpleModule jodaDateTimeSerializationModule() { public SimpleModule jodaDateTimeSerializationModule(
JacksonProperties jacksonProperties) {
SimpleModule module = new SimpleModule(); SimpleModule module = new SimpleModule();
JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(); JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(
jacksonProperties);
if (jacksonJodaFormat != null) { if (jacksonJodaFormat != null) {
module.addSerializer(DateTime.class, module.addSerializer(DateTime.class,
new DateTimeSerializer(jacksonJodaFormat, 0)); new DateTimeSerializer(jacksonJodaFormat, 0));
@ -133,17 +129,17 @@ public class JacksonAutoConfiguration {
return module; return module;
} }
private JacksonJodaDateFormat getJacksonJodaDateFormat() { private JacksonJodaDateFormat getJacksonJodaDateFormat(
if (this.jacksonProperties.getJodaDateTimeFormat() != null) { JacksonProperties jacksonProperties) {
if (jacksonProperties.getJodaDateTimeFormat() != null) {
return new JacksonJodaDateFormat(DateTimeFormat return new JacksonJodaDateFormat(DateTimeFormat
.forPattern(this.jacksonProperties.getJodaDateTimeFormat()) .forPattern(jacksonProperties.getJodaDateTimeFormat())
.withZoneUTC()); .withZoneUTC());
} }
if (this.jacksonProperties.getDateFormat() != null) { if (jacksonProperties.getDateFormat() != null) {
try { try {
return new JacksonJodaDateFormat(DateTimeFormat return new JacksonJodaDateFormat(DateTimeFormat
.forPattern(this.jacksonProperties.getDateFormat()) .forPattern(jacksonProperties.getDateFormat()).withZoneUTC());
.withZoneUTC());
} }
catch (IllegalArgumentException ex) { catch (IllegalArgumentException ex) {
if (logger.isWarnEnabled()) { if (logger.isWarnEnabled()) {
@ -175,18 +171,13 @@ public class JacksonAutoConfiguration {
@ConditionalOnClass(Jackson2ObjectMapperBuilder.class) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
static class JacksonObjectMapperBuilderConfiguration { static class JacksonObjectMapperBuilderConfiguration {
private final ApplicationContext applicationContext;
JacksonObjectMapperBuilderConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder( public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(
ApplicationContext applicationContext,
List<Jackson2ObjectMapperBuilderCustomizer> customizers) { List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.applicationContext(this.applicationContext); builder.applicationContext(applicationContext);
customize(builder, customizers); customize(builder, customizers);
return builder; return builder;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,26 +52,14 @@ public class DataSourceTransactionManagerAutoConfiguration {
@ConditionalOnSingleCandidate(DataSource.class) @ConditionalOnSingleCandidate(DataSource.class)
static class DataSourceTransactionManagerConfiguration { static class DataSourceTransactionManagerConfiguration {
private final DataSource dataSource;
private final TransactionManagerCustomizers transactionManagerCustomizers;
DataSourceTransactionManagerConfiguration(DataSource dataSource,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
this.dataSource = dataSource;
this.transactionManagerCustomizers = transactionManagerCustomizers
.getIfAvailable();
}
@Bean @Bean
@ConditionalOnMissingBean(PlatformTransactionManager.class) @ConditionalOnMissingBean(PlatformTransactionManager.class)
public DataSourceTransactionManager transactionManager( public DataSourceTransactionManager transactionManager(DataSource dataSource,
DataSourceProperties properties) { ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager( DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(
this.dataSource); dataSource);
if (this.transactionManagerCustomizers != null) { transactionManagerCustomizers.ifAvailable(
this.transactionManagerCustomizers.customize(transactionManager); (customizers) -> customizers.customize(transactionManager));
}
return transactionManager; return transactionManager;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,8 +16,6 @@
package org.springframework.boot.autoconfigure.jdbc; package org.springframework.boot.autoconfigure.jdbc;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
@ -37,34 +35,18 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
@EnableConfigurationProperties(DataSourceProperties.class) @EnableConfigurationProperties(DataSourceProperties.class)
public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware { public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware {
private EmbeddedDatabase database;
private ClassLoader classLoader; private ClassLoader classLoader;
private final DataSourceProperties properties;
public EmbeddedDataSourceConfiguration(DataSourceProperties properties) {
this.properties = properties;
}
@Override @Override
public void setBeanClassLoader(ClassLoader classLoader) { public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader; this.classLoader = classLoader;
} }
@Bean @Bean(destroyMethod = "shutdown")
public EmbeddedDatabase dataSource() { public EmbeddedDatabase dataSource(DataSourceProperties properties) {
this.database = new EmbeddedDatabaseBuilder() return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()) .setType(EmbeddedDatabaseConnection.get(this.classLoader).getType())
.setName(this.properties.determineDatabaseName()).build(); .setName(properties.determineDatabaseName()).build();
return this.database;
}
@PreDestroy
public void close() {
if (this.database != null) {
this.database.shutdown();
}
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,21 +53,13 @@ public class JdbcTemplateAutoConfiguration {
@Configuration @Configuration
static class JdbcTemplateConfiguration { static class JdbcTemplateConfiguration {
private final DataSource dataSource;
private final JdbcProperties properties;
JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
this.dataSource = dataSource;
this.properties = properties;
}
@Bean @Bean
@Primary @Primary
@ConditionalOnMissingBean(JdbcOperations.class) @ConditionalOnMissingBean(JdbcOperations.class)
public JdbcTemplate jdbcTemplate() { public JdbcTemplate jdbcTemplate(DataSource dataSource,
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); JdbcProperties properties) {
JdbcProperties.Template template = this.properties.getTemplate(); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
JdbcProperties.Template template = properties.getTemplate();
jdbcTemplate.setFetchSize(template.getFetchSize()); jdbcTemplate.setFetchSize(template.getFetchSize());
jdbcTemplate.setMaxRows(template.getMaxRows()); jdbcTemplate.setMaxRows(template.getMaxRows());
if (template.getQueryTimeout() != null) { if (template.getQueryTimeout() != null) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -48,24 +48,20 @@ import org.springframework.jmx.support.JmxUtils;
@EnableConfigurationProperties(DataSourceProperties.class) @EnableConfigurationProperties(DataSourceProperties.class)
public class JndiDataSourceAutoConfiguration { public class JndiDataSourceAutoConfiguration {
private final ApplicationContext context;
public JndiDataSourceAutoConfiguration(ApplicationContext context) {
this.context = context;
}
@Bean(destroyMethod = "") @Bean(destroyMethod = "")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public DataSource dataSource(DataSourceProperties properties) { public DataSource dataSource(DataSourceProperties properties,
ApplicationContext context) {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
DataSource dataSource = dataSourceLookup.getDataSource(properties.getJndiName()); DataSource dataSource = dataSourceLookup.getDataSource(properties.getJndiName());
excludeMBeanIfNecessary(dataSource, "dataSource"); excludeMBeanIfNecessary(dataSource, "dataSource", context);
return dataSource; return dataSource;
} }
private void excludeMBeanIfNecessary(Object candidate, String beanName) { private void excludeMBeanIfNecessary(Object candidate, String beanName,
for (MBeanExporter mbeanExporter : this.context ApplicationContext context) {
.getBeansOfType(MBeanExporter.class).values()) { for (MBeanExporter mbeanExporter : context.getBeansOfType(MBeanExporter.class)
.values()) {
if (JmxUtils.isMBean(candidate.getClass())) { if (JmxUtils.isMBean(candidate.getClass())) {
mbeanExporter.addExcludedBean(beanName); mbeanExporter.addExcludedBean(beanName);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -61,28 +61,14 @@ import org.springframework.util.StringUtils;
@ConditionalOnMissingBean(DataSource.class) @ConditionalOnMissingBean(DataSource.class)
public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { public class XADataSourceAutoConfiguration implements BeanClassLoaderAware {
private final XADataSourceWrapper wrapper;
private final DataSourceProperties properties;
private final XADataSource xaDataSource;
private ClassLoader classLoader; private ClassLoader classLoader;
public XADataSourceAutoConfiguration(XADataSourceWrapper wrapper,
DataSourceProperties properties, ObjectProvider<XADataSource> xaDataSource) {
this.wrapper = wrapper;
this.properties = properties;
this.xaDataSource = xaDataSource.getIfAvailable();
}
@Bean @Bean
public DataSource dataSource() throws Exception { public DataSource dataSource(XADataSourceWrapper wrapper,
XADataSource xaDataSource = this.xaDataSource; DataSourceProperties properties, ObjectProvider<XADataSource> xaDataSource)
if (xaDataSource == null) { throws Exception {
xaDataSource = createXaDataSource(); return wrapper.wrapDataSource(
} xaDataSource.getIfAvailable(() -> createXaDataSource(properties)));
return this.wrapper.wrapDataSource(xaDataSource);
} }
@Override @Override
@ -90,16 +76,16 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware {
this.classLoader = classLoader; this.classLoader = classLoader;
} }
private XADataSource createXaDataSource() { private XADataSource createXaDataSource(DataSourceProperties properties) {
String className = this.properties.getXa().getDataSourceClassName(); String className = properties.getXa().getDataSourceClassName();
if (!StringUtils.hasLength(className)) { if (!StringUtils.hasLength(className)) {
className = DatabaseDriver.fromJdbcUrl(this.properties.determineUrl()) className = DatabaseDriver.fromJdbcUrl(properties.determineUrl())
.getXaDataSourceClassName(); .getXaDataSourceClassName();
} }
Assert.state(StringUtils.hasLength(className), Assert.state(StringUtils.hasLength(className),
"No XA DataSource class name specified"); "No XA DataSource class name specified");
XADataSource dataSource = createXaDataSourceInstance(className); XADataSource dataSource = createXaDataSourceInstance(className);
bindXaProperties(dataSource, this.properties); bindXaProperties(dataSource, properties);
return dataSource; return dataSource;
} }
@ -125,9 +111,9 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware {
private ConfigurationPropertySource getBinderSource( private ConfigurationPropertySource getBinderSource(
DataSourceProperties dataSourceProperties) { DataSourceProperties dataSourceProperties) {
MapConfigurationPropertySource source = new MapConfigurationPropertySource(); MapConfigurationPropertySource source = new MapConfigurationPropertySource();
source.put("user", this.properties.determineUsername()); source.put("user", dataSourceProperties.determineUsername());
source.put("password", this.properties.determinePassword()); source.put("password", dataSourceProperties.determinePassword());
source.put("url", this.properties.determineUrl()); source.put("url", dataSourceProperties.determineUrl());
source.putAll(dataSourceProperties.getXa().getProperties()); source.putAll(dataSourceProperties.getXa().getProperties());
ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
aliases.addAliases("user", "username"); aliases.addAliases("user", "username");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -55,28 +55,23 @@ public class JndiConnectionFactoryAutoConfiguration {
private static final String[] JNDI_LOCATIONS = { "java:/JmsXA", private static final String[] JNDI_LOCATIONS = { "java:/JmsXA",
"java:/XAConnectionFactory" }; "java:/XAConnectionFactory" };
private final JmsProperties properties;
private final JndiLocatorDelegate jndiLocatorDelegate;
public JndiConnectionFactoryAutoConfiguration(JmsProperties properties) {
this.properties = properties;
this.jndiLocatorDelegate = JndiLocatorDelegate.createDefaultResourceRefLocator();
}
@Bean @Bean
public ConnectionFactory connectionFactory() throws NamingException { public ConnectionFactory connectionFactory(JmsProperties properties)
if (StringUtils.hasLength(this.properties.getJndiName())) { throws NamingException {
return this.jndiLocatorDelegate.lookup(this.properties.getJndiName(), JndiLocatorDelegate jndiLocatorDelegate = JndiLocatorDelegate
.createDefaultResourceRefLocator();
if (StringUtils.hasLength(properties.getJndiName())) {
return jndiLocatorDelegate.lookup(properties.getJndiName(),
ConnectionFactory.class); ConnectionFactory.class);
} }
return findJndiConnectionFactory(); return findJndiConnectionFactory(jndiLocatorDelegate);
} }
private ConnectionFactory findJndiConnectionFactory() { private ConnectionFactory findJndiConnectionFactory(
JndiLocatorDelegate jndiLocatorDelegate) {
for (String name : JNDI_LOCATIONS) { for (String name : JNDI_LOCATIONS) {
try { try {
return this.jndiLocatorDelegate.lookup(name, ConnectionFactory.class); return jndiLocatorDelegate.lookup(name, ConnectionFactory.class);
} }
catch (NamingException ex) { catch (NamingException ex) {
// Swallow and continue // Swallow and continue

View File

@ -54,16 +54,12 @@ class ActiveMQConnectionFactoryConfiguration {
@ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", matchIfMissing = true) @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", matchIfMissing = true)
static class SimpleConnectionFactoryConfiguration { static class SimpleConnectionFactoryConfiguration {
private final JmsProperties jmsProperties;
private final ActiveMQProperties properties; private final ActiveMQProperties properties;
private final List<ActiveMQConnectionFactoryCustomizer> connectionFactoryCustomizers; private final List<ActiveMQConnectionFactoryCustomizer> connectionFactoryCustomizers;
SimpleConnectionFactoryConfiguration(JmsProperties jmsProperties, SimpleConnectionFactoryConfiguration(ActiveMQProperties properties,
ActiveMQProperties properties,
ObjectProvider<ActiveMQConnectionFactoryCustomizer> connectionFactoryCustomizers) { ObjectProvider<ActiveMQConnectionFactoryCustomizer> connectionFactoryCustomizers) {
this.jmsProperties = jmsProperties;
this.properties = properties; this.properties = properties;
this.connectionFactoryCustomizers = connectionFactoryCustomizers this.connectionFactoryCustomizers = connectionFactoryCustomizers
.orderedStream().collect(Collectors.toList()); .orderedStream().collect(Collectors.toList());
@ -71,8 +67,9 @@ class ActiveMQConnectionFactoryConfiguration {
@Bean @Bean
@ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", matchIfMissing = true)
public CachingConnectionFactory cachingJmsConnectionFactory() { public CachingConnectionFactory cachingJmsConnectionFactory(
JmsProperties.Cache cacheProperties = this.jmsProperties.getCache(); JmsProperties jmsProperties) {
JmsProperties.Cache cacheProperties = jmsProperties.getCache();
CachingConnectionFactory connectionFactory = new CachingConnectionFactory( CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
createConnectionFactory()); createConnectionFactory());
connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheConsumers(cacheProperties.isConsumers());

View File

@ -48,23 +48,21 @@ class ArtemisConnectionFactoryConfiguration {
@ConditionalOnProperty(prefix = "spring.artemis.pool", name = "enabled", havingValue = "false", matchIfMissing = true) @ConditionalOnProperty(prefix = "spring.artemis.pool", name = "enabled", havingValue = "false", matchIfMissing = true)
static class SimpleConnectionFactoryConfiguration { static class SimpleConnectionFactoryConfiguration {
private final JmsProperties jmsProperties;
private final ArtemisProperties properties; private final ArtemisProperties properties;
private final ListableBeanFactory beanFactory; private final ListableBeanFactory beanFactory;
SimpleConnectionFactoryConfiguration(JmsProperties jmsProperties, SimpleConnectionFactoryConfiguration(ArtemisProperties properties,
ArtemisProperties properties, ListableBeanFactory beanFactory) { ListableBeanFactory beanFactory) {
this.jmsProperties = jmsProperties;
this.properties = properties; this.properties = properties;
this.beanFactory = beanFactory; this.beanFactory = beanFactory;
} }
@Bean @Bean
@ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnProperty(prefix = "spring.jms.cache", name = "enabled", havingValue = "true", matchIfMissing = true)
public CachingConnectionFactory cachingJmsConnectionFactory() { public CachingConnectionFactory cachingJmsConnectionFactory(
JmsProperties.Cache cacheProperties = this.jmsProperties.getCache(); JmsProperties jmsProperties) {
JmsProperties.Cache cacheProperties = jmsProperties.getCache();
CachingConnectionFactory connectionFactory = new CachingConnectionFactory( CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
createConnectionFactory()); createConnectionFactory());
connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheConsumers(cacheProperties.isConsumers());

View File

@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.jms.artemis; package org.springframework.boot.autoconfigure.jms.artemis;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -49,22 +48,8 @@ class ArtemisEmbeddedServerConfiguration {
private final ArtemisProperties properties; private final ArtemisProperties properties;
private final ObjectProvider<ArtemisConfigurationCustomizer> configurationCustomizers; ArtemisEmbeddedServerConfiguration(ArtemisProperties properties) {
private final List<JMSQueueConfiguration> queuesConfiguration;
private final List<TopicConfiguration> topicsConfiguration;
ArtemisEmbeddedServerConfiguration(ArtemisProperties properties,
ObjectProvider<ArtemisConfigurationCustomizer> configurationCustomizers,
ObjectProvider<JMSQueueConfiguration> queuesConfiguration,
ObjectProvider<TopicConfiguration> topicsConfiguration) {
this.properties = properties; this.properties = properties;
this.configurationCustomizers = configurationCustomizers;
this.queuesConfiguration = queuesConfiguration.orderedStream()
.collect(Collectors.toList());
this.topicsConfiguration = topicsConfiguration.orderedStream()
.collect(Collectors.toList());
} }
@Bean @Bean
@ -78,35 +63,33 @@ class ArtemisEmbeddedServerConfiguration {
@ConditionalOnMissingBean @ConditionalOnMissingBean
public EmbeddedJMS artemisServer( public EmbeddedJMS artemisServer(
org.apache.activemq.artemis.core.config.Configuration configuration, org.apache.activemq.artemis.core.config.Configuration configuration,
JMSConfiguration jmsConfiguration) { JMSConfiguration jmsConfiguration,
ObjectProvider<ArtemisConfigurationCustomizer> configurationCustomizers) {
EmbeddedJMS server = new EmbeddedJMS(); EmbeddedJMS server = new EmbeddedJMS();
customize(configuration); configurationCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(configuration));
server.setConfiguration(configuration); server.setConfiguration(configuration);
server.setJmsConfiguration(jmsConfiguration); server.setJmsConfiguration(jmsConfiguration);
server.setRegistry(new ArtemisNoOpBindingRegistry()); server.setRegistry(new ArtemisNoOpBindingRegistry());
return server; return server;
} }
private void customize(
org.apache.activemq.artemis.core.config.Configuration configuration) {
this.configurationCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(configuration));
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public JMSConfiguration artemisJmsConfiguration() { public JMSConfiguration artemisJmsConfiguration(
ObjectProvider<JMSQueueConfiguration> queuesConfiguration,
ObjectProvider<TopicConfiguration> topicsConfiguration) {
JMSConfiguration configuration = new JMSConfigurationImpl(); JMSConfiguration configuration = new JMSConfigurationImpl();
addAll(configuration.getQueueConfigurations(), this.queuesConfiguration); addAll(configuration.getQueueConfigurations(), queuesConfiguration);
addAll(configuration.getTopicConfigurations(), this.topicsConfiguration); addAll(configuration.getTopicConfigurations(), topicsConfiguration);
addQueues(configuration, this.properties.getEmbedded().getQueues()); addQueues(configuration, this.properties.getEmbedded().getQueues());
addTopics(configuration, this.properties.getEmbedded().getTopics()); addTopics(configuration, this.properties.getEmbedded().getTopics());
return configuration; return configuration;
} }
private <T> void addAll(List<T> list, Collection<? extends T> items) { private <T> void addAll(List<T> list, ObjectProvider<T> items) {
if (items != null) { if (items != null) {
list.addAll(items); list.addAll(items.orderedStream().collect(Collectors.toList()));
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,15 +18,12 @@ package org.springframework.boot.autoconfigure.jmx;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.context.annotation.EnableMBeanExport;
@ -54,33 +51,26 @@ import org.springframework.util.StringUtils;
@Configuration @Configuration
@ConditionalOnClass({ MBeanExporter.class }) @ConditionalOnClass({ MBeanExporter.class })
@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true)
public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware { public class JmxAutoConfiguration {
private Environment environment; private final Environment environment;
private BeanFactory beanFactory; public JmxAutoConfiguration(Environment environment) {
@Override
public void setEnvironment(Environment environment) {
this.environment = environment; this.environment = environment;
} }
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Bean @Bean
@Primary @Primary
@ConditionalOnMissingBean(value = MBeanExporter.class, search = SearchStrategy.CURRENT) @ConditionalOnMissingBean(value = MBeanExporter.class, search = SearchStrategy.CURRENT)
public AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy) { public AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy,
BeanFactory beanFactory) {
AnnotationMBeanExporter exporter = new AnnotationMBeanExporter(); AnnotationMBeanExporter exporter = new AnnotationMBeanExporter();
exporter.setRegistrationPolicy(RegistrationPolicy.FAIL_ON_EXISTING); exporter.setRegistrationPolicy(RegistrationPolicy.FAIL_ON_EXISTING);
exporter.setNamingStrategy(namingStrategy); exporter.setNamingStrategy(namingStrategy);
String serverBean = this.environment.getProperty("spring.jmx.server", String serverBean = this.environment.getProperty("spring.jmx.server",
"mbeanServer"); "mbeanServer");
if (StringUtils.hasLength(serverBean)) { if (StringUtils.hasLength(serverBean)) {
exporter.setServer(this.beanFactory.getBean(serverBean, MBeanServer.class)); exporter.setServer(beanFactory.getBean(serverBean, MBeanServer.class));
} }
return exporter; return exporter;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -90,56 +90,6 @@ public class JooqAutoConfiguration {
@EnableConfigurationProperties(JooqProperties.class) @EnableConfigurationProperties(JooqProperties.class)
public static class DslContextConfiguration { public static class DslContextConfiguration {
private final JooqProperties properties;
private final ConnectionProvider connection;
private final DataSource dataSource;
private final TransactionProvider transactionProvider;
private final RecordMapperProvider recordMapperProvider;
private final RecordUnmapperProvider recordUnmapperProvider;
private final Settings settings;
private final RecordListenerProvider[] recordListenerProviders;
private final ExecuteListenerProvider[] executeListenerProviders;
private final VisitListenerProvider[] visitListenerProviders;
private final TransactionListenerProvider[] transactionListenerProviders;
private final ExecutorProvider executorProvider;
public DslContextConfiguration(JooqProperties properties,
ConnectionProvider connectionProvider, DataSource dataSource,
ObjectProvider<TransactionProvider> transactionProvider,
ObjectProvider<RecordMapperProvider> recordMapperProvider,
ObjectProvider<RecordUnmapperProvider> recordUnmapperProvider,
ObjectProvider<Settings> settings,
ObjectProvider<RecordListenerProvider[]> recordListenerProviders,
ExecuteListenerProvider[] executeListenerProviders,
ObjectProvider<VisitListenerProvider[]> visitListenerProviders,
ObjectProvider<TransactionListenerProvider[]> transactionListenerProviders,
ObjectProvider<ExecutorProvider> executorProvider) {
this.properties = properties;
this.connection = connectionProvider;
this.dataSource = dataSource;
this.transactionProvider = transactionProvider.getIfAvailable();
this.recordMapperProvider = recordMapperProvider.getIfAvailable();
this.recordUnmapperProvider = recordUnmapperProvider.getIfAvailable();
this.settings = settings.getIfAvailable();
this.recordListenerProviders = recordListenerProviders.getIfAvailable();
this.executeListenerProviders = executeListenerProviders;
this.visitListenerProviders = visitListenerProviders.getIfAvailable();
this.transactionListenerProviders = transactionListenerProviders
.getIfAvailable();
this.executorProvider = executorProvider.getIfAvailable();
}
@Bean @Bean
public DefaultDSLContext dslContext(org.jooq.Configuration configuration) { public DefaultDSLContext dslContext(org.jooq.Configuration configuration) {
return new DefaultDSLContext(configuration); return new DefaultDSLContext(configuration);
@ -147,30 +97,33 @@ public class JooqAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(org.jooq.Configuration.class) @ConditionalOnMissingBean(org.jooq.Configuration.class)
public DefaultConfiguration jooqConfiguration() { public DefaultConfiguration jooqConfiguration(JooqProperties properties,
ConnectionProvider connectionProvider, DataSource dataSource,
ObjectProvider<TransactionProvider> transactionProvider,
ObjectProvider<RecordMapperProvider> recordMapperProvider,
ObjectProvider<RecordUnmapperProvider> recordUnmapperProvider,
ObjectProvider<Settings> settings,
ObjectProvider<RecordListenerProvider> recordListenerProviders,
ObjectProvider<ExecuteListenerProvider> executeListenerProviders,
ObjectProvider<VisitListenerProvider> visitListenerProviders,
ObjectProvider<TransactionListenerProvider> transactionListenerProviders,
ObjectProvider<ExecutorProvider> executorProvider) {
DefaultConfiguration configuration = new DefaultConfiguration(); DefaultConfiguration configuration = new DefaultConfiguration();
configuration.set(this.properties.determineSqlDialect(this.dataSource)); configuration.set(properties.determineSqlDialect(dataSource));
configuration.set(this.connection); configuration.set(connectionProvider);
if (this.transactionProvider != null) { transactionProvider.ifAvailable(configuration::set);
configuration.set(this.transactionProvider); recordMapperProvider.ifAvailable(configuration::set);
} recordUnmapperProvider.ifAvailable(configuration::set);
if (this.recordMapperProvider != null) { settings.ifAvailable(configuration::set);
configuration.set(this.recordMapperProvider); executorProvider.ifAvailable(configuration::set);
} configuration.set(recordListenerProviders.orderedStream()
if (this.recordUnmapperProvider != null) { .toArray(RecordListenerProvider[]::new));
configuration.set(this.recordUnmapperProvider); configuration.set(executeListenerProviders.orderedStream()
} .toArray(ExecuteListenerProvider[]::new));
if (this.settings != null) { configuration.set(visitListenerProviders.orderedStream()
configuration.set(this.settings); .toArray(VisitListenerProvider[]::new));
} configuration.setTransactionListenerProvider(transactionListenerProviders
if (this.executorProvider != null) { .orderedStream().toArray(TransactionListenerProvider[]::new));
configuration.set(this.executorProvider);
}
configuration.set(this.recordListenerProviders);
configuration.set(this.executeListenerProviders);
configuration.set(this.visitListenerProviders);
configuration
.setTransactionListenerProvider(this.transactionListenerProviders);
return configuration; return configuration;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,24 +58,19 @@ public class KafkaAutoConfiguration {
private final KafkaProperties properties; private final KafkaProperties properties;
private final RecordMessageConverter messageConverter; public KafkaAutoConfiguration(KafkaProperties properties) {
public KafkaAutoConfiguration(KafkaProperties properties,
ObjectProvider<RecordMessageConverter> messageConverter) {
this.properties = properties; this.properties = properties;
this.messageConverter = messageConverter.getIfUnique();
} }
@Bean @Bean
@ConditionalOnMissingBean(KafkaTemplate.class) @ConditionalOnMissingBean(KafkaTemplate.class)
public KafkaTemplate<?, ?> kafkaTemplate( public KafkaTemplate<?, ?> kafkaTemplate(
ProducerFactory<Object, Object> kafkaProducerFactory, ProducerFactory<Object, Object> kafkaProducerFactory,
ProducerListener<Object, Object> kafkaProducerListener) { ProducerListener<Object, Object> kafkaProducerListener,
ObjectProvider<RecordMessageConverter> messageConverter) {
KafkaTemplate<Object, Object> kafkaTemplate = new KafkaTemplate<>( KafkaTemplate<Object, Object> kafkaTemplate = new KafkaTemplate<>(
kafkaProducerFactory); kafkaProducerFactory);
if (this.messageConverter != null) { messageConverter.ifUnique(kafkaTemplate::setMessageConverter);
kafkaTemplate.setMessageConverter(this.messageConverter);
}
kafkaTemplate.setProducerListener(kafkaProducerListener); kafkaTemplate.setProducerListener(kafkaProducerListener);
kafkaTemplate.setDefaultTopic(this.properties.getTemplate().getDefaultTopic()); kafkaTemplate.setDefaultTopic(this.properties.getTemplate().getDefaultTopic());
return kafkaTemplate; return kafkaTemplate;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,26 +42,18 @@ import org.springframework.ldap.core.support.LdapContextSource;
@EnableConfigurationProperties(LdapProperties.class) @EnableConfigurationProperties(LdapProperties.class)
public class LdapAutoConfiguration { public class LdapAutoConfiguration {
private final LdapProperties properties;
private final Environment environment;
public LdapAutoConfiguration(LdapProperties properties, Environment environment) {
this.properties = properties;
this.environment = environment;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public LdapContextSource ldapContextSource() { public LdapContextSource ldapContextSource(LdapProperties properties,
Environment environment) {
LdapContextSource source = new LdapContextSource(); LdapContextSource source = new LdapContextSource();
source.setUserDn(this.properties.getUsername()); source.setUserDn(properties.getUsername());
source.setPassword(this.properties.getPassword()); source.setPassword(properties.getPassword());
source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly()); source.setAnonymousReadOnly(properties.getAnonymousReadOnly());
source.setBase(this.properties.getBase()); source.setBase(properties.getBase());
source.setUrls(this.properties.determineUrls(this.environment)); source.setUrls(properties.determineUrls(environment));
source.setBaseEnvironmentProperties( source.setBaseEnvironmentProperties(
Collections.unmodifiableMap(this.properties.getBaseEnvironment())); Collections.unmodifiableMap(properties.getBaseEnvironment()));
return source; return source;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -80,38 +80,29 @@ public class EmbeddedLdapAutoConfiguration {
private final EmbeddedLdapProperties embeddedProperties; private final EmbeddedLdapProperties embeddedProperties;
private final LdapProperties properties;
private final ConfigurableApplicationContext applicationContext;
private final Environment environment;
private InMemoryDirectoryServer server; private InMemoryDirectoryServer server;
public EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties, public EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties) {
LdapProperties properties, ConfigurableApplicationContext applicationContext,
Environment environment) {
this.embeddedProperties = embeddedProperties; this.embeddedProperties = embeddedProperties;
this.properties = properties;
this.applicationContext = applicationContext;
this.environment = environment;
} }
@Bean @Bean
@DependsOn("directoryServer") @DependsOn("directoryServer")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public LdapContextSource ldapContextSource() { public LdapContextSource ldapContextSource(Environment environment,
LdapProperties properties) {
LdapContextSource source = new LdapContextSource(); LdapContextSource source = new LdapContextSource();
if (hasCredentials(this.embeddedProperties.getCredential())) { if (hasCredentials(this.embeddedProperties.getCredential())) {
source.setUserDn(this.embeddedProperties.getCredential().getUsername()); source.setUserDn(this.embeddedProperties.getCredential().getUsername());
source.setPassword(this.embeddedProperties.getCredential().getPassword()); source.setPassword(this.embeddedProperties.getCredential().getPassword());
} }
source.setUrls(this.properties.determineUrls(this.environment)); source.setUrls(properties.determineUrls(environment));
return source; return source;
} }
@Bean @Bean
public InMemoryDirectoryServer directoryServer() throws LDAPException { public InMemoryDirectoryServer directoryServer(ApplicationContext applicationContext)
throws LDAPException {
String[] baseDn = StringUtils.toStringArray(this.embeddedProperties.getBaseDn()); String[] baseDn = StringUtils.toStringArray(this.embeddedProperties.getBaseDn());
InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(baseDn); InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(baseDn);
if (hasCredentials(this.embeddedProperties.getCredential())) { if (hasCredentials(this.embeddedProperties.getCredential())) {
@ -124,9 +115,9 @@ public class EmbeddedLdapAutoConfiguration {
.createLDAPConfig("LDAP", this.embeddedProperties.getPort()); .createLDAPConfig("LDAP", this.embeddedProperties.getPort());
config.setListenerConfigs(listenerConfig); config.setListenerConfigs(listenerConfig);
this.server = new InMemoryDirectoryServer(config); this.server = new InMemoryDirectoryServer(config);
importLdif(); importLdif(applicationContext);
this.server.startListening(); this.server.startListening();
setPortProperty(this.applicationContext, this.server.getListenPort()); setPortProperty(applicationContext, this.server.getListenPort());
return this.server; return this.server;
} }
@ -158,11 +149,11 @@ public class EmbeddedLdapAutoConfiguration {
&& StringUtils.hasText(credential.getPassword()); && StringUtils.hasText(credential.getPassword());
} }
private void importLdif() throws LDAPException { private void importLdif(ApplicationContext applicationContext) throws LDAPException {
String location = this.embeddedProperties.getLdif(); String location = this.embeddedProperties.getLdif();
if (StringUtils.hasText(location)) { if (StringUtils.hasText(location)) {
try { try {
Resource resource = this.applicationContext.getResource(location); Resource resource = applicationContext.getResource(location);
if (resource.exists()) { if (resource.exists()) {
try (InputStream inputStream = resource.getInputStream()) { try (InputStream inputStream = resource.getInputStream()) {
this.server.importFromLDIF(true, new LDIFReader(inputStream)); this.server.importFromLDIF(true, new LDIFReader(inputStream));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -83,23 +83,12 @@ public class LiquibaseAutoConfiguration {
private final LiquibaseProperties properties; private final LiquibaseProperties properties;
private final DataSourceProperties dataSourceProperties;
private final ResourceLoader resourceLoader; private final ResourceLoader resourceLoader;
private final DataSource dataSource;
private final DataSource liquibaseDataSource;
public LiquibaseConfiguration(LiquibaseProperties properties, public LiquibaseConfiguration(LiquibaseProperties properties,
DataSourceProperties dataSourceProperties, ResourceLoader resourceLoader, ResourceLoader resourceLoader) {
ObjectProvider<DataSource> dataSource,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource) {
this.properties = properties; this.properties = properties;
this.dataSourceProperties = dataSourceProperties;
this.resourceLoader = resourceLoader; this.resourceLoader = resourceLoader;
this.dataSource = dataSource.getIfUnique();
this.liquibaseDataSource = liquibaseDataSource.getIfAvailable();
} }
@PostConstruct @PostConstruct
@ -115,8 +104,12 @@ public class LiquibaseAutoConfiguration {
} }
@Bean @Bean
public SpringLiquibase liquibase() { public SpringLiquibase liquibase(DataSourceProperties dataSourceProperties,
SpringLiquibase liquibase = createSpringLiquibase(); ObjectProvider<DataSource> dataSource,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource) {
SpringLiquibase liquibase = createSpringLiquibase(
liquibaseDataSource.getIfAvailable(), dataSource.getIfUnique(),
dataSourceProperties);
liquibase.setChangeLog(this.properties.getChangeLog()); liquibase.setChangeLog(this.properties.getChangeLog());
liquibase.setContexts(this.properties.getContexts()); liquibase.setContexts(this.properties.getContexts());
liquibase.setDefaultSchema(this.properties.getDefaultSchema()); liquibase.setDefaultSchema(this.properties.getDefaultSchema());
@ -135,35 +128,39 @@ public class LiquibaseAutoConfiguration {
return liquibase; return liquibase;
} }
private SpringLiquibase createSpringLiquibase() { private SpringLiquibase createSpringLiquibase(DataSource liquibaseDatasource,
DataSource liquibaseDataSource = getDataSource(); DataSource dataSource, DataSourceProperties dataSourceProperties) {
DataSource liquibaseDataSource = getDataSource(liquibaseDatasource,
dataSource);
if (liquibaseDataSource != null) { if (liquibaseDataSource != null) {
SpringLiquibase liquibase = new SpringLiquibase(); SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(liquibaseDataSource); liquibase.setDataSource(liquibaseDataSource);
return liquibase; return liquibase;
} }
SpringLiquibase liquibase = new DataSourceClosingSpringLiquibase(); SpringLiquibase liquibase = new DataSourceClosingSpringLiquibase();
liquibase.setDataSource(createNewDataSource()); liquibase.setDataSource(createNewDataSource(dataSourceProperties));
return liquibase; return liquibase;
} }
private DataSource getDataSource() { private DataSource getDataSource(DataSource liquibaseDataSource,
if (this.liquibaseDataSource != null) { DataSource dataSource) {
return this.liquibaseDataSource; if (liquibaseDataSource != null) {
return liquibaseDataSource;
} }
if (this.properties.getUrl() == null && this.properties.getUser() == null) { if (this.properties.getUrl() == null && this.properties.getUser() == null) {
return this.dataSource; return dataSource;
} }
return null; return null;
} }
private DataSource createNewDataSource() { private DataSource createNewDataSource(
DataSourceProperties dataSourceProperties) {
String url = getProperty(this.properties::getUrl, String url = getProperty(this.properties::getUrl,
this.dataSourceProperties::getUrl); dataSourceProperties::getUrl);
String user = getProperty(this.properties::getUser, String user = getProperty(this.properties::getUser,
this.dataSourceProperties::getUsername); dataSourceProperties::getUsername);
String password = getProperty(this.properties::getPassword, String password = getProperty(this.properties::getPassword,
this.dataSourceProperties::getPassword); dataSourceProperties::getPassword);
return DataSourceBuilder.create().url(url).username(user).password(password) return DataSourceBuilder.create().url(url).username(user).password(password)
.build(); .build();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -37,33 +37,27 @@ import org.springframework.mail.javamail.JavaMailSenderImpl;
@ConditionalOnProperty(prefix = "spring.mail", name = "host") @ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration { class MailSenderPropertiesConfiguration {
private final MailProperties properties;
MailSenderPropertiesConfiguration(MailProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public JavaMailSenderImpl mailSender() { public JavaMailSenderImpl mailSender(MailProperties properties) {
JavaMailSenderImpl sender = new JavaMailSenderImpl(); JavaMailSenderImpl sender = new JavaMailSenderImpl();
applyProperties(sender); applyProperties(properties, sender);
return sender; return sender;
} }
private void applyProperties(JavaMailSenderImpl sender) { private void applyProperties(MailProperties properties, JavaMailSenderImpl sender) {
sender.setHost(this.properties.getHost()); sender.setHost(properties.getHost());
if (this.properties.getPort() != null) { if (properties.getPort() != null) {
sender.setPort(this.properties.getPort()); sender.setPort(properties.getPort());
} }
sender.setUsername(this.properties.getUsername()); sender.setUsername(properties.getUsername());
sender.setPassword(this.properties.getPassword()); sender.setPassword(properties.getPassword());
sender.setProtocol(this.properties.getProtocol()); sender.setProtocol(properties.getProtocol());
if (this.properties.getDefaultEncoding() != null) { if (properties.getDefaultEncoding() != null) {
sender.setDefaultEncoding(this.properties.getDefaultEncoding().name()); sender.setDefaultEncoding(properties.getDefaultEncoding().name());
} }
if (!this.properties.getProperties().isEmpty()) { if (!properties.getProperties().isEmpty()) {
sender.setJavaMailProperties(asProperties(this.properties.getProperties())); sender.setJavaMailProperties(asProperties(properties.getProperties()));
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,8 +16,6 @@
package org.springframework.boot.autoconfigure.mongo; package org.springframework.boot.autoconfigure.mongo;
import javax.annotation.PreDestroy;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions;
@ -45,31 +43,13 @@ import org.springframework.core.env.Environment;
@ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDbFactory") @ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDbFactory")
public class MongoAutoConfiguration { public class MongoAutoConfiguration {
private final MongoClientOptions options;
private final MongoClientFactory factory;
private MongoClient mongo;
public MongoAutoConfiguration(MongoProperties properties,
ObjectProvider<MongoClientOptions> options, Environment environment) {
this.options = options.getIfAvailable();
this.factory = new MongoClientFactory(properties, environment);
}
@PreDestroy
public void close() {
if (this.mongo != null) {
this.mongo.close();
}
}
@Bean @Bean
@ConditionalOnMissingBean(type = { "com.mongodb.MongoClient", @ConditionalOnMissingBean(type = { "com.mongodb.MongoClient",
"com.mongodb.client.MongoClient" }) "com.mongodb.client.MongoClient" })
public MongoClient mongo() { public MongoClient mongo(MongoProperties properties,
this.mongo = this.factory.createMongoClient(this.options); ObjectProvider<MongoClientOptions> options, Environment environment) {
return this.mongo; return new MongoClientFactory(properties, environment)
.createMongoClient(options.getIfAvailable());
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,8 +18,6 @@ package org.springframework.boot.autoconfigure.mongo;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.PreDestroy;
import com.mongodb.MongoClientSettings; import com.mongodb.MongoClientSettings;
import com.mongodb.connection.netty.NettyStreamFactoryFactory; import com.mongodb.connection.netty.NettyStreamFactoryFactory;
import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClient;
@ -49,31 +47,16 @@ import org.springframework.core.env.Environment;
@EnableConfigurationProperties(MongoProperties.class) @EnableConfigurationProperties(MongoProperties.class)
public class MongoReactiveAutoConfiguration { public class MongoReactiveAutoConfiguration {
private final MongoClientSettings settings;
private MongoClient mongo;
public MongoReactiveAutoConfiguration(ObjectProvider<MongoClientSettings> settings) {
this.settings = settings.getIfAvailable();
}
@PreDestroy
public void close() {
if (this.mongo != null) {
this.mongo.close();
}
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public MongoClient reactiveStreamsMongoClient(MongoProperties properties, public MongoClient reactiveStreamsMongoClient(MongoProperties properties,
Environment environment, Environment environment,
ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers) { ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers,
ObjectProvider<MongoClientSettings> settings) {
ReactiveMongoClientFactory factory = new ReactiveMongoClientFactory(properties, ReactiveMongoClientFactory factory = new ReactiveMongoClientFactory(properties,
environment, environment,
builderCustomizers.orderedStream().collect(Collectors.toList())); builderCustomizers.orderedStream().collect(Collectors.toList()));
this.mongo = factory.createMongoClient(this.settings); return factory.createMongoClient(settings.getIfAvailable());
return this.mongo;
} }
@Configuration @Configuration

View File

@ -92,30 +92,20 @@ public class EmbeddedMongoAutoConfiguration {
private final MongoProperties properties; private final MongoProperties properties;
private final EmbeddedMongoProperties embeddedProperties;
private final ApplicationContext context;
private final IRuntimeConfig runtimeConfig;
public EmbeddedMongoAutoConfiguration(MongoProperties properties, public EmbeddedMongoAutoConfiguration(MongoProperties properties,
EmbeddedMongoProperties embeddedProperties, ApplicationContext context, EmbeddedMongoProperties embeddedProperties) {
IRuntimeConfig runtimeConfig) {
this.properties = properties; this.properties = properties;
this.embeddedProperties = embeddedProperties;
this.context = context;
this.runtimeConfig = runtimeConfig;
} }
@Bean(initMethod = "start", destroyMethod = "stop") @Bean(initMethod = "start", destroyMethod = "stop")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig) public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig,
throws IOException { IRuntimeConfig runtimeConfig, ApplicationContext context) throws IOException {
Integer configuredPort = this.properties.getPort(); Integer configuredPort = this.properties.getPort();
if (configuredPort == null || configuredPort == 0) { if (configuredPort == null || configuredPort == 0) {
setEmbeddedPort(mongodConfig.net().getPort()); setEmbeddedPort(context, mongodConfig.net().getPort());
} }
MongodStarter mongodStarter = getMongodStarter(this.runtimeConfig); MongodStarter mongodStarter = getMongodStarter(runtimeConfig);
return mongodStarter.prepare(mongodConfig); return mongodStarter.prepare(mongodConfig);
} }
@ -128,10 +118,11 @@ public class EmbeddedMongoAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public IMongodConfig embeddedMongoConfiguration() throws IOException { public IMongodConfig embeddedMongoConfiguration(
EmbeddedMongoProperties embeddedProperties) throws IOException {
MongodConfigBuilder builder = new MongodConfigBuilder() MongodConfigBuilder builder = new MongodConfigBuilder()
.version(determineVersion()); .version(determineVersion(embeddedProperties));
EmbeddedMongoProperties.Storage storage = this.embeddedProperties.getStorage(); EmbeddedMongoProperties.Storage storage = embeddedProperties.getStorage();
if (storage != null) { if (storage != null) {
String databaseDir = storage.getDatabaseDir(); String databaseDir = storage.getDatabaseDir();
String replSetName = storage.getReplSetName(); String replSetName = storage.getReplSetName();
@ -151,20 +142,19 @@ public class EmbeddedMongoAutoConfiguration {
return builder.build(); return builder.build();
} }
private IFeatureAwareVersion determineVersion() { private IFeatureAwareVersion determineVersion(
if (this.embeddedProperties.getFeatures() == null) { EmbeddedMongoProperties embeddedProperties) {
if (embeddedProperties.getFeatures() == null) {
for (Version version : Version.values()) { for (Version version : Version.values()) {
if (version.asInDownloadPath() if (version.asInDownloadPath().equals(embeddedProperties.getVersion())) {
.equals(this.embeddedProperties.getVersion())) {
return version; return version;
} }
} }
return Versions.withFeatures( return Versions
new GenericVersion(this.embeddedProperties.getVersion())); .withFeatures(new GenericVersion(embeddedProperties.getVersion()));
} }
return Versions.withFeatures( return Versions.withFeatures(new GenericVersion(embeddedProperties.getVersion()),
new GenericVersion(this.embeddedProperties.getVersion()), embeddedProperties.getFeatures().toArray(new Feature[0]));
this.embeddedProperties.getFeatures().toArray(new Feature[0]));
} }
private InetAddress getHost() throws UnknownHostException { private InetAddress getHost() throws UnknownHostException {
@ -175,8 +165,8 @@ public class EmbeddedMongoAutoConfiguration {
return InetAddress.getByName(this.properties.getHost()); return InetAddress.getByName(this.properties.getHost());
} }
private void setEmbeddedPort(int port) { private void setEmbeddedPort(ApplicationContext context, int port) {
setPortProperty(this.context, port); setPortProperty(context, port);
} }
private void setPortProperty(ApplicationContext currentContext, int port) { private void setPortProperty(ApplicationContext currentContext, int port) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,14 +52,11 @@ public class MustacheAutoConfiguration {
private final MustacheProperties mustache; private final MustacheProperties mustache;
private final Environment environment;
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
public MustacheAutoConfiguration(MustacheProperties mustache, Environment environment, public MustacheAutoConfiguration(MustacheProperties mustache,
ApplicationContext applicationContext) { ApplicationContext applicationContext) {
this.mustache = mustache; this.mustache = mustache;
this.environment = environment;
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
@ -78,14 +75,15 @@ public class MustacheAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader) { public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader,
Environment environment) {
return Mustache.compiler().withLoader(mustacheTemplateLoader) return Mustache.compiler().withLoader(mustacheTemplateLoader)
.withCollector(collector()); .withCollector(collector(environment));
} }
private Collector collector() { private Collector collector(Environment environment) {
MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector();
collector.setEnvironment(this.environment); collector.setEnvironment(environment);
return collector; return collector;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,21 +30,16 @@ import org.springframework.core.Ordered;
@ConditionalOnWebApplication(type = Type.REACTIVE) @ConditionalOnWebApplication(type = Type.REACTIVE)
class MustacheReactiveWebConfiguration { class MustacheReactiveWebConfiguration {
private final MustacheProperties mustache;
protected MustacheReactiveWebConfiguration(MustacheProperties mustache) {
this.mustache = mustache;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler) { public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler,
MustacheProperties mustache) {
MustacheViewResolver resolver = new MustacheViewResolver(mustacheCompiler); MustacheViewResolver resolver = new MustacheViewResolver(mustacheCompiler);
resolver.setPrefix(this.mustache.getPrefix()); resolver.setPrefix(mustache.getPrefix());
resolver.setSuffix(this.mustache.getSuffix()); resolver.setSuffix(mustache.getSuffix());
resolver.setViewNames(this.mustache.getViewNames()); resolver.setViewNames(mustache.getViewNames());
resolver.setRequestContextAttribute(this.mustache.getRequestContextAttribute()); resolver.setRequestContextAttribute(mustache.getRequestContextAttribute());
resolver.setCharset(this.mustache.getCharsetName()); resolver.setCharset(mustache.getCharsetName());
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10); resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver; return resolver;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,18 +30,13 @@ import org.springframework.core.Ordered;
@ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnWebApplication(type = Type.SERVLET)
class MustacheServletWebConfiguration { class MustacheServletWebConfiguration {
private final MustacheProperties mustache;
protected MustacheServletWebConfiguration(MustacheProperties mustache) {
this.mustache = mustache;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler) { public MustacheViewResolver mustacheViewResolver(Compiler mustacheCompiler,
MustacheProperties mustache) {
MustacheViewResolver resolver = new MustacheViewResolver(mustacheCompiler); MustacheViewResolver resolver = new MustacheViewResolver(mustacheCompiler);
this.mustache.applyToMvcViewResolver(resolver); mustache.applyToMvcViewResolver(resolver);
resolver.setCharset(this.mustache.getCharsetName()); resolver.setCharset(mustache.getCharsetName());
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10); resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver; return resolver;
} }

View File

@ -36,7 +36,6 @@ import org.hibernate.cfg.AvailableSettings;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate; import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.SchemaManagementProvider; import org.springframework.boot.jdbc.SchemaManagementProvider;
import org.springframework.boot.jdbc.metadata.CompositeDataSourcePoolMetadataProvider; import org.springframework.boot.jdbc.metadata.CompositeDataSourcePoolMetadataProvider;
@ -90,15 +89,13 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration {
HibernateJpaConfiguration(DataSource dataSource, JpaProperties jpaProperties, HibernateJpaConfiguration(DataSource dataSource, JpaProperties jpaProperties,
ConfigurableListableBeanFactory beanFactory, ConfigurableListableBeanFactory beanFactory,
ObjectProvider<JtaTransactionManager> jtaTransactionManager, ObjectProvider<JtaTransactionManager> jtaTransactionManager,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers,
HibernateProperties hibernateProperties, HibernateProperties hibernateProperties,
ObjectProvider<Collection<DataSourcePoolMetadataProvider>> metadataProviders, ObjectProvider<Collection<DataSourcePoolMetadataProvider>> metadataProviders,
ObjectProvider<SchemaManagementProvider> providers, ObjectProvider<SchemaManagementProvider> providers,
ObjectProvider<PhysicalNamingStrategy> physicalNamingStrategy, ObjectProvider<PhysicalNamingStrategy> physicalNamingStrategy,
ObjectProvider<ImplicitNamingStrategy> implicitNamingStrategy, ObjectProvider<ImplicitNamingStrategy> implicitNamingStrategy,
ObjectProvider<HibernatePropertiesCustomizer> hibernatePropertiesCustomizers) { ObjectProvider<HibernatePropertiesCustomizer> hibernatePropertiesCustomizers) {
super(dataSource, jpaProperties, jtaTransactionManager, super(dataSource, jpaProperties, jtaTransactionManager);
transactionManagerCustomizers);
this.hibernateProperties = hibernateProperties; this.hibernateProperties = hibernateProperties;
this.defaultDdlAutoProvider = new HibernateDefaultDdlAutoProvider(providers); this.defaultDdlAutoProvider = new HibernateDefaultDdlAutoProvider(providers);
this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider( this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(

View File

@ -81,27 +81,22 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware {
private final JtaTransactionManager jtaTransactionManager; private final JtaTransactionManager jtaTransactionManager;
private final TransactionManagerCustomizers transactionManagerCustomizers;
private ConfigurableListableBeanFactory beanFactory; private ConfigurableListableBeanFactory beanFactory;
protected JpaBaseConfiguration(DataSource dataSource, JpaProperties properties, protected JpaBaseConfiguration(DataSource dataSource, JpaProperties properties,
ObjectProvider<JtaTransactionManager> jtaTransactionManager, ObjectProvider<JtaTransactionManager> jtaTransactionManager) {
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
this.dataSource = dataSource; this.dataSource = dataSource;
this.properties = properties; this.properties = properties;
this.jtaTransactionManager = jtaTransactionManager.getIfAvailable(); this.jtaTransactionManager = jtaTransactionManager.getIfAvailable();
this.transactionManagerCustomizers = transactionManagerCustomizers
.getIfAvailable();
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public PlatformTransactionManager transactionManager() { public PlatformTransactionManager transactionManager(
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
JpaTransactionManager transactionManager = new JpaTransactionManager(); JpaTransactionManager transactionManager = new JpaTransactionManager();
if (this.transactionManagerCustomizers != null) { transactionManagerCustomizers
this.transactionManagerCustomizers.customize(transactionManager); .ifAvailable((customizers) -> customizers.customize(transactionManager));
}
return transactionManager; return transactionManager;
} }

View File

@ -60,61 +60,37 @@ import org.springframework.transaction.PlatformTransactionManager;
HibernateJpaAutoConfiguration.class }) HibernateJpaAutoConfiguration.class })
public class QuartzAutoConfiguration { public class QuartzAutoConfiguration {
private final QuartzProperties properties;
private final ObjectProvider<SchedulerFactoryBeanCustomizer> customizers;
private final JobDetail[] jobDetails;
private final Map<String, Calendar> calendars;
private final Trigger[] triggers;
private final ApplicationContext applicationContext;
public QuartzAutoConfiguration(QuartzProperties properties,
ObjectProvider<SchedulerFactoryBeanCustomizer> customizers,
ObjectProvider<JobDetail[]> jobDetails, Map<String, Calendar> calendars,
ObjectProvider<Trigger[]> triggers, ApplicationContext applicationContext) {
this.properties = properties;
this.customizers = customizers;
this.jobDetails = jobDetails.getIfAvailable();
this.calendars = calendars;
this.triggers = triggers.getIfAvailable();
this.applicationContext = applicationContext;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SchedulerFactoryBean quartzScheduler() { public SchedulerFactoryBean quartzScheduler(QuartzProperties properties,
ObjectProvider<SchedulerFactoryBeanCustomizer> customizers,
ObjectProvider<JobDetail> jobDetails, Map<String, Calendar> calendars,
ObjectProvider<Trigger> triggers, ApplicationContext applicationContext) {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
SpringBeanJobFactory jobFactory = new SpringBeanJobFactory(); SpringBeanJobFactory jobFactory = new SpringBeanJobFactory();
jobFactory.setApplicationContext(this.applicationContext); jobFactory.setApplicationContext(applicationContext);
schedulerFactoryBean.setJobFactory(jobFactory); schedulerFactoryBean.setJobFactory(jobFactory);
if (this.properties.getSchedulerName() != null) { if (properties.getSchedulerName() != null) {
schedulerFactoryBean.setSchedulerName(this.properties.getSchedulerName()); schedulerFactoryBean.setSchedulerName(properties.getSchedulerName());
} }
schedulerFactoryBean.setAutoStartup(this.properties.isAutoStartup()); schedulerFactoryBean.setAutoStartup(properties.isAutoStartup());
schedulerFactoryBean schedulerFactoryBean
.setStartupDelay((int) this.properties.getStartupDelay().getSeconds()); .setStartupDelay((int) properties.getStartupDelay().getSeconds());
schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown( schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown(
this.properties.isWaitForJobsToCompleteOnShutdown()); properties.isWaitForJobsToCompleteOnShutdown());
schedulerFactoryBean schedulerFactoryBean
.setOverwriteExistingJobs(this.properties.isOverwriteExistingJobs()); .setOverwriteExistingJobs(properties.isOverwriteExistingJobs());
if (!this.properties.getProperties().isEmpty()) { if (!properties.getProperties().isEmpty()) {
schedulerFactoryBean schedulerFactoryBean
.setQuartzProperties(asProperties(this.properties.getProperties())); .setQuartzProperties(asProperties(properties.getProperties()));
} }
if (this.jobDetails != null && this.jobDetails.length > 0) { schedulerFactoryBean
schedulerFactoryBean.setJobDetails(this.jobDetails); .setJobDetails(jobDetails.orderedStream().toArray(JobDetail[]::new));
} schedulerFactoryBean.setCalendars(calendars);
if (this.calendars != null && !this.calendars.isEmpty()) { schedulerFactoryBean
schedulerFactoryBean.setCalendars(this.calendars); .setTriggers(triggers.orderedStream().toArray(Trigger[]::new));
} customizers.orderedStream()
if (this.triggers != null && this.triggers.length > 0) { .forEach((customizer) -> customizer.customize(schedulerFactoryBean));
schedulerFactoryBean.setTriggers(this.triggers);
}
customize(schedulerFactoryBean);
return schedulerFactoryBean; return schedulerFactoryBean;
} }
@ -124,11 +100,6 @@ public class QuartzAutoConfiguration {
return properties; return properties;
} }
private void customize(SchedulerFactoryBean schedulerFactoryBean) {
this.customizers.orderedStream()
.forEach((customizer) -> customizer.customize(schedulerFactoryBean));
}
@Configuration @Configuration
@ConditionalOnSingleCandidate(DataSource.class) @ConditionalOnSingleCandidate(DataSource.class)
protected static class JdbcStoreTypeConfiguration { protected static class JdbcStoreTypeConfiguration {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,19 +58,14 @@ import org.springframework.security.oauth2.client.web.server.ServerOAuth2Authori
@ConditionalOnClass({ Flux.class, EnableWebFluxSecurity.class, ClientRegistration.class }) @ConditionalOnClass({ Flux.class, EnableWebFluxSecurity.class, ClientRegistration.class })
public class ReactiveOAuth2ClientAutoConfiguration { public class ReactiveOAuth2ClientAutoConfiguration {
private final OAuth2ClientProperties properties;
public ReactiveOAuth2ClientAutoConfiguration(OAuth2ClientProperties properties) {
this.properties = properties;
}
@Bean @Bean
@Conditional(ClientsConfiguredCondition.class) @Conditional(ClientsConfiguredCondition.class)
@ConditionalOnMissingBean(ReactiveClientRegistrationRepository.class) @ConditionalOnMissingBean(ReactiveClientRegistrationRepository.class)
public InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() { public InMemoryReactiveClientRegistrationRepository clientRegistrationRepository(
OAuth2ClientProperties properties) {
List<ClientRegistration> registrations = new ArrayList<>( List<ClientRegistration> registrations = new ArrayList<>(
OAuth2ClientPropertiesRegistrationAdapter OAuth2ClientPropertiesRegistrationAdapter
.getClientRegistrations(this.properties).values()); .getClientRegistrations(properties).values());
return new InMemoryReactiveClientRegistrationRepository(registrations); return new InMemoryReactiveClientRegistrationRepository(registrations);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,18 +42,13 @@ import org.springframework.security.oauth2.client.registration.InMemoryClientReg
@Conditional(ClientsConfiguredCondition.class) @Conditional(ClientsConfiguredCondition.class)
class OAuth2ClientRegistrationRepositoryConfiguration { class OAuth2ClientRegistrationRepositoryConfiguration {
private final OAuth2ClientProperties properties;
OAuth2ClientRegistrationRepositoryConfiguration(OAuth2ClientProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean(ClientRegistrationRepository.class) @ConditionalOnMissingBean(ClientRegistrationRepository.class)
public InMemoryClientRegistrationRepository clientRegistrationRepository() { public InMemoryClientRegistrationRepository clientRegistrationRepository(
OAuth2ClientProperties properties) {
List<ClientRegistration> registrations = new ArrayList<>( List<ClientRegistration> registrations = new ArrayList<>(
OAuth2ClientPropertiesRegistrationAdapter OAuth2ClientPropertiesRegistrationAdapter
.getClientRegistrations(this.properties).values()); .getClientRegistrations(properties).values());
return new InMemoryClientRegistrationRepository(registrations); return new InMemoryClientRegistrationRepository(registrations);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,17 +33,12 @@ import org.springframework.security.web.server.SecurityWebFilterChain;
@ConditionalOnBean(ReactiveJwtDecoder.class) @ConditionalOnBean(ReactiveJwtDecoder.class)
class ReactiveOAuth2ResourceServerWebSecurityConfiguration { class ReactiveOAuth2ResourceServerWebSecurityConfiguration {
private final ReactiveJwtDecoder jwtDecoder;
ReactiveOAuth2ResourceServerWebSecurityConfiguration(ReactiveJwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ReactiveJwtDecoder jwtDecoder) {
http.authorizeExchange().anyExchange().authenticated().and() http.authorizeExchange().anyExchange().authenticated().and()
.oauth2ResourceServer().jwt().jwtDecoder(this.jwtDecoder); .oauth2ResourceServer().jwt().jwtDecoder(jwtDecoder);
return http.build(); return http.build();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,22 +43,16 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties(SendGridProperties.class) @EnableConfigurationProperties(SendGridProperties.class)
public class SendGridAutoConfiguration { public class SendGridAutoConfiguration {
private final SendGridProperties properties;
public SendGridAutoConfiguration(SendGridProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SendGrid sendGrid() { public SendGrid sendGrid(SendGridProperties properties) {
if (this.properties.isProxyConfigured()) { if (properties.isProxyConfigured()) {
HttpHost proxy = new HttpHost(this.properties.getProxy().getHost(), HttpHost proxy = new HttpHost(properties.getProxy().getHost(),
this.properties.getProxy().getPort()); properties.getProxy().getPort());
return new SendGrid(this.properties.getApiKey(), return new SendGrid(properties.getApiKey(),
new Client(HttpClientBuilder.create().setProxy(proxy).build())); new Client(HttpClientBuilder.create().setProxy(proxy).build()));
} }
return new SendGrid(this.properties.getApiKey()); return new SendGrid(properties.getApiKey());
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,7 +32,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* {@link EnableAutoConfiguration Auto-configuration} for Solr 4.x. * {@link EnableAutoConfiguration Auto-configuration} for Solr.
* *
* @author Christoph Strobl * @author Christoph Strobl
* @since 1.1.0 * @since 1.1.0
@ -42,27 +42,14 @@ import org.springframework.util.StringUtils;
@EnableConfigurationProperties(SolrProperties.class) @EnableConfigurationProperties(SolrProperties.class)
public class SolrAutoConfiguration { public class SolrAutoConfiguration {
private final SolrProperties properties;
private SolrClient solrClient;
public SolrAutoConfiguration(SolrProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SolrClient solrClient() { public SolrClient solrClient(SolrProperties properties) {
this.solrClient = createSolrClient(); if (StringUtils.hasText(properties.getZkHost())) {
return this.solrClient; return new CloudSolrClient.Builder(Arrays.asList(properties.getZkHost()),
}
private SolrClient createSolrClient() {
if (StringUtils.hasText(this.properties.getZkHost())) {
return new CloudSolrClient.Builder(Arrays.asList(this.properties.getZkHost()),
Optional.empty()).build(); Optional.empty()).build();
} }
return new HttpSolrClient.Builder(this.properties.getHost()).build(); return new HttpSolrClient.Builder(properties.getHost()).build();
} }
} }

View File

@ -51,36 +51,24 @@ public class TaskExecutionAutoConfiguration {
*/ */
public static final String APPLICATION_TASK_EXECUTOR_BEAN_NAME = "applicationTaskExecutor"; public static final String APPLICATION_TASK_EXECUTOR_BEAN_NAME = "applicationTaskExecutor";
private final TaskExecutionProperties properties;
private final ObjectProvider<TaskExecutorCustomizer> taskExecutorCustomizers;
private final ObjectProvider<TaskDecorator> taskDecorator;
public TaskExecutionAutoConfiguration(TaskExecutionProperties properties,
ObjectProvider<TaskExecutorCustomizer> taskExecutorCustomizers,
ObjectProvider<TaskDecorator> taskDecorator) {
this.properties = properties;
this.taskExecutorCustomizers = taskExecutorCustomizers;
this.taskDecorator = taskDecorator;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public TaskExecutorBuilder taskExecutorBuilder() { public TaskExecutorBuilder taskExecutorBuilder(TaskExecutionProperties properties,
TaskExecutionProperties.Pool pool = this.properties.getPool(); ObjectProvider<TaskExecutorCustomizer> taskExecutorCustomizers,
ObjectProvider<TaskDecorator> taskDecorator) {
TaskExecutionProperties.Pool pool = properties.getPool();
TaskExecutorBuilder builder = new TaskExecutorBuilder(); TaskExecutorBuilder builder = new TaskExecutorBuilder();
builder = builder.queueCapacity(pool.getQueueCapacity()); builder = builder.queueCapacity(pool.getQueueCapacity());
builder = builder.corePoolSize(pool.getCoreSize()); builder = builder.corePoolSize(pool.getCoreSize());
builder = builder.maxPoolSize(pool.getMaxSize()); builder = builder.maxPoolSize(pool.getMaxSize());
builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout()); builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout());
builder = builder.keepAlive(pool.getKeepAlive()); builder = builder.keepAlive(pool.getKeepAlive());
Shutdown shutdown = this.properties.getShutdown(); Shutdown shutdown = properties.getShutdown();
builder = builder.awaitTermination(shutdown.isAwaitTermination()); builder = builder.awaitTermination(shutdown.isAwaitTermination());
builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod()); builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
builder = builder.threadNamePrefix(this.properties.getThreadNamePrefix()); builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
builder = builder.customizers(this.taskExecutorCustomizers); builder = builder.customizers(taskExecutorCustomizers);
builder = builder.taskDecorator(this.taskDecorator.getIfUnique()); builder = builder.taskDecorator(taskDecorator.getIfUnique());
return builder; return builder;
} }

View File

@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.thymeleaf; package org.springframework.boot.autoconfigure.thymeleaf;
import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@ -136,29 +135,17 @@ public class ThymeleafAutoConfiguration {
@Configuration @Configuration
protected static class ThymeleafDefaultConfiguration { protected static class ThymeleafDefaultConfiguration {
private final ThymeleafProperties properties;
private final Collection<ITemplateResolver> templateResolvers;
private final ObjectProvider<IDialect> dialects;
public ThymeleafDefaultConfiguration(ThymeleafProperties properties,
Collection<ITemplateResolver> templateResolvers,
ObjectProvider<IDialect> dialectsProvider) {
this.properties = properties;
this.templateResolvers = templateResolvers;
this.dialects = dialectsProvider;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SpringTemplateEngine templateEngine() { public SpringTemplateEngine templateEngine(ThymeleafProperties properties,
ObjectProvider<ITemplateResolver> templateResolvers,
ObjectProvider<IDialect> dialects) {
SpringTemplateEngine engine = new SpringTemplateEngine(); SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(this.properties.isEnableSpringElCompiler()); engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler());
engine.setRenderHiddenMarkersBeforeCheckboxes( engine.setRenderHiddenMarkersBeforeCheckboxes(
this.properties.isRenderHiddenMarkersBeforeCheckboxes()); properties.isRenderHiddenMarkersBeforeCheckboxes());
this.templateResolvers.forEach(engine::addTemplateResolver); templateResolvers.orderedStream().forEach(engine::addTemplateResolver);
this.dialects.orderedStream().forEach(engine::addDialect); dialects.orderedStream().forEach(engine::addDialect);
return engine; return engine;
} }
@ -182,33 +169,24 @@ public class ThymeleafAutoConfiguration {
@Configuration @Configuration
static class ThymeleafViewResolverConfiguration { static class ThymeleafViewResolverConfiguration {
private final ThymeleafProperties properties;
private final SpringTemplateEngine templateEngine;
ThymeleafViewResolverConfiguration(ThymeleafProperties properties,
SpringTemplateEngine templateEngine) {
this.properties = properties;
this.templateEngine = templateEngine;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver") @ConditionalOnMissingBean(name = "thymeleafViewResolver")
public ThymeleafViewResolver thymeleafViewResolver() { public ThymeleafViewResolver thymeleafViewResolver(
ThymeleafProperties properties, SpringTemplateEngine templateEngine) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver(); ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(this.templateEngine); resolver.setTemplateEngine(templateEngine);
resolver.setCharacterEncoding(this.properties.getEncoding().name()); resolver.setCharacterEncoding(properties.getEncoding().name());
resolver.setContentType( resolver.setContentType(
appendCharset(this.properties.getServlet().getContentType(), appendCharset(properties.getServlet().getContentType(),
resolver.getCharacterEncoding())); resolver.getCharacterEncoding()));
resolver.setProducePartialOutputWhileProcessing(this.properties resolver.setProducePartialOutputWhileProcessing(
.getServlet().isProducePartialOutputWhileProcessing()); properties.getServlet().isProducePartialOutputWhileProcessing());
resolver.setExcludedViewNames(this.properties.getExcludedViewNames()); resolver.setExcludedViewNames(properties.getExcludedViewNames());
resolver.setViewNames(this.properties.getViewNames()); resolver.setViewNames(properties.getViewNames());
// This resolver acts as a fallback resolver (e.g. like a // This resolver acts as a fallback resolver (e.g. like a
// InternalResourceViewResolver) so it needs to have low precedence // InternalResourceViewResolver) so it needs to have low precedence
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5);
resolver.setCache(this.properties.isCache()); resolver.setCache(properties.isCache());
return resolver; return resolver;
} }
@ -231,29 +209,17 @@ public class ThymeleafAutoConfiguration {
@ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true)
static class ThymeleafReactiveConfiguration { static class ThymeleafReactiveConfiguration {
private final ThymeleafProperties properties;
private final Collection<ITemplateResolver> templateResolvers;
private final ObjectProvider<IDialect> dialects;
ThymeleafReactiveConfiguration(ThymeleafProperties properties,
Collection<ITemplateResolver> templateResolvers,
ObjectProvider<IDialect> dialectsProvider) {
this.properties = properties;
this.templateResolvers = templateResolvers;
this.dialects = dialectsProvider;
}
@Bean @Bean
@ConditionalOnMissingBean(ISpringWebFluxTemplateEngine.class) @ConditionalOnMissingBean(ISpringWebFluxTemplateEngine.class)
public SpringWebFluxTemplateEngine templateEngine() { public SpringWebFluxTemplateEngine templateEngine(ThymeleafProperties properties,
ObjectProvider<ITemplateResolver> templateResolvers,
ObjectProvider<IDialect> dialects) {
SpringWebFluxTemplateEngine engine = new SpringWebFluxTemplateEngine(); SpringWebFluxTemplateEngine engine = new SpringWebFluxTemplateEngine();
engine.setEnableSpringELCompiler(this.properties.isEnableSpringElCompiler()); engine.setEnableSpringELCompiler(properties.isEnableSpringElCompiler());
engine.setRenderHiddenMarkersBeforeCheckboxes( engine.setRenderHiddenMarkersBeforeCheckboxes(
this.properties.isRenderHiddenMarkersBeforeCheckboxes()); properties.isRenderHiddenMarkersBeforeCheckboxes());
this.templateResolvers.forEach(engine::addTemplateResolver); templateResolvers.orderedStream().forEach(engine::addTemplateResolver);
this.dialects.orderedStream().forEach(engine::addDialect); dialects.orderedStream().forEach(engine::addDialect);
return engine; return engine;
} }
@ -264,20 +230,15 @@ public class ThymeleafAutoConfiguration {
@ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true)
static class ThymeleafWebFluxConfiguration { static class ThymeleafWebFluxConfiguration {
private final ThymeleafProperties properties;
ThymeleafWebFluxConfiguration(ThymeleafProperties properties) {
this.properties = properties;
}
@Bean @Bean
@ConditionalOnMissingBean(name = "thymeleafReactiveViewResolver") @ConditionalOnMissingBean(name = "thymeleafReactiveViewResolver")
public ThymeleafReactiveViewResolver thymeleafViewResolver( public ThymeleafReactiveViewResolver thymeleafViewResolver(
ISpringWebFluxTemplateEngine templateEngine) { ISpringWebFluxTemplateEngine templateEngine,
ThymeleafProperties properties) {
ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver(); ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver();
resolver.setTemplateEngine(templateEngine); resolver.setTemplateEngine(templateEngine);
mapProperties(this.properties, resolver); mapProperties(properties, resolver);
mapReactiveProperties(this.properties.getReactive(), resolver); mapReactiveProperties(properties.getReactive(), resolver);
// This resolver acts as a fallback resolver (e.g. like a // This resolver acts as a fallback resolver (e.g. like a
// InternalResourceViewResolver) so it needs to have low precedence // InternalResourceViewResolver) so it needs to have low precedence
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -64,17 +64,11 @@ public class TransactionAutoConfiguration {
@ConditionalOnSingleCandidate(PlatformTransactionManager.class) @ConditionalOnSingleCandidate(PlatformTransactionManager.class)
public static class TransactionTemplateConfiguration { public static class TransactionTemplateConfiguration {
private final PlatformTransactionManager transactionManager;
public TransactionTemplateConfiguration(
PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public TransactionTemplate transactionTemplate() { public TransactionTemplate transactionTemplate(
return new TransactionTemplate(this.transactionManager); PlatformTransactionManager transactionManager) {
return new TransactionTemplate(transactionManager);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -61,34 +61,24 @@ import org.springframework.util.StringUtils;
@ConditionalOnMissingBean(PlatformTransactionManager.class) @ConditionalOnMissingBean(PlatformTransactionManager.class)
class AtomikosJtaConfiguration { class AtomikosJtaConfiguration {
private final JtaProperties jtaProperties;
private final TransactionManagerCustomizers transactionManagerCustomizers;
AtomikosJtaConfiguration(JtaProperties jtaProperties,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
this.jtaProperties = jtaProperties;
this.transactionManagerCustomizers = transactionManagerCustomizers
.getIfAvailable();
}
@Bean(initMethod = "init", destroyMethod = "shutdownWait") @Bean(initMethod = "init", destroyMethod = "shutdownWait")
@ConditionalOnMissingBean(UserTransactionService.class) @ConditionalOnMissingBean(UserTransactionService.class)
public UserTransactionServiceImp userTransactionService( public UserTransactionServiceImp userTransactionService(
AtomikosProperties atomikosProperties) { AtomikosProperties atomikosProperties, JtaProperties jtaProperties) {
Properties properties = new Properties(); Properties properties = new Properties();
if (StringUtils.hasText(this.jtaProperties.getTransactionManagerId())) { if (StringUtils.hasText(jtaProperties.getTransactionManagerId())) {
properties.setProperty("com.atomikos.icatch.tm_unique_name", properties.setProperty("com.atomikos.icatch.tm_unique_name",
this.jtaProperties.getTransactionManagerId()); jtaProperties.getTransactionManagerId());
} }
properties.setProperty("com.atomikos.icatch.log_base_dir", getLogBaseDir()); properties.setProperty("com.atomikos.icatch.log_base_dir",
getLogBaseDir(jtaProperties));
properties.putAll(atomikosProperties.asProperties()); properties.putAll(atomikosProperties.asProperties());
return new UserTransactionServiceImp(properties); return new UserTransactionServiceImp(properties);
} }
private String getLogBaseDir() { private String getLogBaseDir(JtaProperties jtaProperties) {
if (StringUtils.hasLength(this.jtaProperties.getLogDir())) { if (StringUtils.hasLength(jtaProperties.getLogDir())) {
return this.jtaProperties.getLogDir(); return jtaProperties.getLogDir();
} }
File home = new ApplicationHome().getDir(); File home = new ApplicationHome().getDir();
return new File(home, "transaction-logs").getAbsolutePath(); return new File(home, "transaction-logs").getAbsolutePath();
@ -118,12 +108,12 @@ class AtomikosJtaConfiguration {
@Bean @Bean
public JtaTransactionManager transactionManager(UserTransaction userTransaction, public JtaTransactionManager transactionManager(UserTransaction userTransaction,
TransactionManager transactionManager) { TransactionManager transactionManager,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(
userTransaction, transactionManager); userTransaction, transactionManager);
if (this.transactionManagerCustomizers != null) { transactionManagerCustomizers.ifAvailable(
this.transactionManagerCustomizers.customize(jtaTransactionManager); (customizers) -> customizers.customize(jtaTransactionManager));
}
return jtaTransactionManager; return jtaTransactionManager;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,6 +20,7 @@ import java.io.File;
import javax.jms.Message; import javax.jms.Message;
import javax.transaction.TransactionManager; import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import bitronix.tm.BitronixTransactionManager; import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices; import bitronix.tm.TransactionManagerServices;
@ -58,35 +59,24 @@ import org.springframework.util.StringUtils;
@ConditionalOnMissingBean(PlatformTransactionManager.class) @ConditionalOnMissingBean(PlatformTransactionManager.class)
class BitronixJtaConfiguration { class BitronixJtaConfiguration {
private final JtaProperties jtaProperties;
private final TransactionManagerCustomizers transactionManagerCustomizers;
BitronixJtaConfiguration(JtaProperties jtaProperties,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
this.jtaProperties = jtaProperties;
this.transactionManagerCustomizers = transactionManagerCustomizers
.getIfAvailable();
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConfigurationProperties(prefix = "spring.jta.bitronix.properties") @ConfigurationProperties(prefix = "spring.jta.bitronix.properties")
public bitronix.tm.Configuration bitronixConfiguration() { public bitronix.tm.Configuration bitronixConfiguration(JtaProperties jtaProperties) {
bitronix.tm.Configuration config = TransactionManagerServices.getConfiguration(); bitronix.tm.Configuration config = TransactionManagerServices.getConfiguration();
if (StringUtils.hasText(this.jtaProperties.getTransactionManagerId())) { if (StringUtils.hasText(jtaProperties.getTransactionManagerId())) {
config.setServerId(this.jtaProperties.getTransactionManagerId()); config.setServerId(jtaProperties.getTransactionManagerId());
} }
File logBaseDir = getLogBaseDir(); File logBaseDir = getLogBaseDir(jtaProperties);
config.setLogPart1Filename(new File(logBaseDir, "part1.btm").getAbsolutePath()); config.setLogPart1Filename(new File(logBaseDir, "part1.btm").getAbsolutePath());
config.setLogPart2Filename(new File(logBaseDir, "part2.btm").getAbsolutePath()); config.setLogPart2Filename(new File(logBaseDir, "part2.btm").getAbsolutePath());
config.setDisableJmx(true); config.setDisableJmx(true);
return config; return config;
} }
private File getLogBaseDir() { private File getLogBaseDir(JtaProperties jtaProperties) {
if (StringUtils.hasLength(this.jtaProperties.getLogDir())) { if (StringUtils.hasLength(jtaProperties.getLogDir())) {
return new File(this.jtaProperties.getLogDir()); return new File(jtaProperties.getLogDir());
} }
File home = new ApplicationHome().getDir(); File home = new ApplicationHome().getDir();
return new File(home, "transaction-logs"); return new File(home, "transaction-logs");
@ -113,13 +103,13 @@ class BitronixJtaConfiguration {
} }
@Bean @Bean
public JtaTransactionManager transactionManager( public JtaTransactionManager transactionManager(UserTransaction userTransaction,
TransactionManager transactionManager) { TransactionManager transactionManager,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(
transactionManager); userTransaction, transactionManager);
if (this.transactionManagerCustomizers != null) { transactionManagerCustomizers.ifAvailable(
this.transactionManagerCustomizers.customize(jtaTransactionManager); (customizers) -> customizers.customize(jtaTransactionManager));
}
return jtaTransactionManager; return jtaTransactionManager;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,21 +43,13 @@ import org.springframework.transaction.jta.JtaTransactionManager;
@ConditionalOnMissingBean(PlatformTransactionManager.class) @ConditionalOnMissingBean(PlatformTransactionManager.class)
class JndiJtaConfiguration { class JndiJtaConfiguration {
private final TransactionManagerCustomizers transactionManagerCustomizers;
JndiJtaConfiguration(
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
this.transactionManagerCustomizers = transactionManagerCustomizers
.getIfAvailable();
}
@Bean @Bean
public JtaTransactionManager transactionManager() { public JtaTransactionManager transactionManager(
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean() JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean()
.getObject(); .getObject();
if (this.transactionManagerCustomizers != null) { transactionManagerCustomizers.ifAvailable(
this.transactionManagerCustomizers.customize(jtaTransactionManager); (customizers) -> customizers.customize(jtaTransactionManager));
}
return jtaTransactionManager; return jtaTransactionManager;
} }

View File

@ -35,7 +35,6 @@ import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
/** /**
@ -51,29 +50,19 @@ import org.springframework.web.client.RestTemplate;
@Conditional(NotReactiveWebApplicationCondition.class) @Conditional(NotReactiveWebApplicationCondition.class)
public class RestTemplateAutoConfiguration { public class RestTemplateAutoConfiguration {
private final ObjectProvider<HttpMessageConverters> messageConverters;
private final ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers;
public RestTemplateAutoConfiguration(
ObjectProvider<HttpMessageConverters> messageConverters,
ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers) {
this.messageConverters = messageConverters;
this.restTemplateCustomizers = restTemplateCustomizers;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder() { public RestTemplateBuilder restTemplateBuilder(
ObjectProvider<HttpMessageConverters> messageConverters,
ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers) {
RestTemplateBuilder builder = new RestTemplateBuilder(); RestTemplateBuilder builder = new RestTemplateBuilder();
HttpMessageConverters converters = this.messageConverters.getIfUnique(); HttpMessageConverters converters = messageConverters.getIfUnique();
if (converters != null) { if (converters != null) {
builder = builder.messageConverters(converters.getConverters()); builder = builder.messageConverters(converters.getConverters());
} }
List<RestTemplateCustomizer> customizers = restTemplateCustomizers.orderedStream()
List<RestTemplateCustomizer> customizers = this.restTemplateCustomizers .collect(Collectors.toList());
.orderedStream().collect(Collectors.toList()); if (!customizers.isEmpty()) {
if (!CollectionUtils.isEmpty(customizers)) {
builder = builder.customizers(customizers); builder = builder.customizers(customizers);
} }
return builder; return builder;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.web.reactive.error; package org.springframework.boot.autoconfigure.web.reactive.error;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
@ -57,38 +56,25 @@ public class ErrorWebFluxAutoConfiguration {
private final ServerProperties serverProperties; private final ServerProperties serverProperties;
private final ApplicationContext applicationContext; public ErrorWebFluxAutoConfiguration(ServerProperties serverProperties) {
private final ResourceProperties resourceProperties;
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public ErrorWebFluxAutoConfiguration(ServerProperties serverProperties,
ResourceProperties resourceProperties,
ObjectProvider<ViewResolver> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer,
ApplicationContext applicationContext) {
this.serverProperties = serverProperties; this.serverProperties = serverProperties;
this.applicationContext = applicationContext;
this.resourceProperties = resourceProperties;
this.viewResolvers = viewResolversProvider.orderedStream()
.collect(Collectors.toList());
this.serverCodecConfigurer = serverCodecConfigurer;
} }
@Bean @Bean
@ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT) @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT)
@Order(-1) @Order(-1)
public ErrorWebExceptionHandler errorWebExceptionHandler( public ErrorWebExceptionHandler errorWebExceptionHandler(
ErrorAttributes errorAttributes) { ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
ObjectProvider<ViewResolver> viewResolvers,
ServerCodecConfigurer serverCodecConfigurer,
ApplicationContext applicationContext) {
DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler( DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler(
errorAttributes, this.resourceProperties, errorAttributes, resourceProperties, this.serverProperties.getError(),
this.serverProperties.getError(), this.applicationContext); applicationContext);
exceptionHandler.setViewResolvers(this.viewResolvers); exceptionHandler.setViewResolvers(
exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters()); viewResolvers.orderedStream().collect(Collectors.toList()));
exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders()); exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
return exceptionHandler; return exceptionHandler;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -85,27 +85,18 @@ public class DispatcherServletAutoConfiguration {
@EnableConfigurationProperties({ HttpProperties.class, WebMvcProperties.class }) @EnableConfigurationProperties({ HttpProperties.class, WebMvcProperties.class })
protected static class DispatcherServletConfiguration { protected static class DispatcherServletConfiguration {
private final HttpProperties httpProperties;
private final WebMvcProperties webMvcProperties;
public DispatcherServletConfiguration(HttpProperties httpProperties,
WebMvcProperties webMvcProperties) {
this.httpProperties = httpProperties;
this.webMvcProperties = webMvcProperties;
}
@Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) @Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() { public DispatcherServlet dispatcherServlet(HttpProperties httpProperties,
WebMvcProperties webMvcProperties) {
DispatcherServlet dispatcherServlet = new DispatcherServlet(); DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setDispatchOptionsRequest( dispatcherServlet.setDispatchOptionsRequest(
this.webMvcProperties.isDispatchOptionsRequest()); webMvcProperties.isDispatchOptionsRequest());
dispatcherServlet.setDispatchTraceRequest( dispatcherServlet
this.webMvcProperties.isDispatchTraceRequest()); .setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());
dispatcherServlet.setThrowExceptionIfNoHandlerFound( dispatcherServlet.setThrowExceptionIfNoHandlerFound(
this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); webMvcProperties.isThrowExceptionIfNoHandlerFound());
dispatcherServlet.setEnableLoggingRequestDetails( dispatcherServlet
this.httpProperties.isLogRequestDetails()); .setEnableLoggingRequestDetails(httpProperties.isLogRequestDetails());
return dispatcherServlet; return dispatcherServlet;
} }
@ -126,29 +117,17 @@ public class DispatcherServletAutoConfiguration {
@Import(DispatcherServletConfiguration.class) @Import(DispatcherServletConfiguration.class)
protected static class DispatcherServletRegistrationConfiguration { protected static class DispatcherServletRegistrationConfiguration {
private final WebMvcProperties webMvcProperties;
private final MultipartConfigElement multipartConfig;
public DispatcherServletRegistrationConfiguration(
WebMvcProperties webMvcProperties,
ObjectProvider<MultipartConfigElement> multipartConfigProvider) {
this.webMvcProperties = webMvcProperties;
this.multipartConfig = multipartConfigProvider.getIfAvailable();
}
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServletRegistrationBean dispatcherServletRegistration( public DispatcherServletRegistrationBean dispatcherServletRegistration(
DispatcherServlet dispatcherServlet) { DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties,
ObjectProvider<MultipartConfigElement> multipartConfig) {
DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean( DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(
dispatcherServlet, this.webMvcProperties.getServlet().getPath()); dispatcherServlet, webMvcProperties.getServlet().getPath());
registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
registration.setLoadOnStartup( registration
this.webMvcProperties.getServlet().getLoadOnStartup()); .setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());
if (this.multipartConfig != null) { multipartConfig.ifAvailable(registration::setMultipartConfig);
registration.setMultipartConfig(this.multipartConfig);
}
return registration; return registration;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.boot.autoconfigure.web.servlet.error; package org.springframework.boot.autoconfigure.web.servlet.error;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -92,17 +91,8 @@ public class ErrorMvcAutoConfiguration {
private final ServerProperties serverProperties; private final ServerProperties serverProperties;
private final DispatcherServletPath dispatcherServletPath; public ErrorMvcAutoConfiguration(ServerProperties serverProperties) {
private final List<ErrorViewResolver> errorViewResolvers;
public ErrorMvcAutoConfiguration(ServerProperties serverProperties,
DispatcherServletPath dispatcherServletPath,
ObjectProvider<ErrorViewResolver> errorViewResolvers) {
this.serverProperties = serverProperties; this.serverProperties = serverProperties;
this.dispatcherServletPath = dispatcherServletPath;
this.errorViewResolvers = errorViewResolvers.orderedStream()
.collect(Collectors.toList());
} }
@Bean @Bean
@ -114,14 +104,16 @@ public class ErrorMvcAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { public BasicErrorController basicErrorController(ErrorAttributes errorAttributes,
ObjectProvider<ErrorViewResolver> errorViewResolvers) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(), return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
this.errorViewResolvers); errorViewResolvers.orderedStream().collect(Collectors.toList()));
} }
@Bean @Bean
public ErrorPageCustomizer errorPageCustomizer() { public ErrorPageCustomizer errorPageCustomizer(
return new ErrorPageCustomizer(this.serverProperties, this.dispatcherServletPath); DispatcherServletPath dispatcherServletPath) {
return new ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
} }
@Bean @Bean

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -66,22 +66,16 @@ import org.springframework.xml.xsd.SimpleXsdSchema;
@AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class) @AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class)
public class WebServicesAutoConfiguration { public class WebServicesAutoConfiguration {
private final WebServicesProperties properties;
public WebServicesAutoConfiguration(WebServicesProperties properties) {
this.properties = properties;
}
@Bean @Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet( public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(
ApplicationContext applicationContext) { ApplicationContext applicationContext, WebServicesProperties properties) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet(); MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext); servlet.setApplicationContext(applicationContext);
String path = this.properties.getPath(); String path = properties.getPath();
String urlMapping = path + (path.endsWith("/") ? "*" : "/*"); String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
ServletRegistrationBean<MessageDispatcherServlet> registration = new ServletRegistrationBean<>( ServletRegistrationBean<MessageDispatcherServlet> registration = new ServletRegistrationBean<>(
servlet, urlMapping); servlet, urlMapping);
WebServicesProperties.Servlet servletProperties = this.properties.getServlet(); WebServicesProperties.Servlet servletProperties = properties.getServlet();
registration.setLoadOnStartup(servletProperties.getLoadOnStartup()); registration.setLoadOnStartup(servletProperties.getLoadOnStartup());
servletProperties.getInit().forEach(registration::addInitParameter); servletProperties.getInit().forEach(registration::addInitParameter);
return registration; return registration;

Some files were not shown because too many files have changed in this diff Show More