Merge branch '2.0.x' into 2.1.x

Closes gh-17078
This commit is contained in:
Andy Wilkinson
2019-06-07 10:50:34 +01:00
2691 changed files with 27746 additions and 46049 deletions

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");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,7 @@ import org.springframework.util.StringUtils;
* @since 1.3.0
* @see BeanDefinition#setDependsOn(String[])
*/
public abstract class AbstractDependsOnBeanFactoryPostProcessor
implements BeanFactoryPostProcessor {
public abstract class AbstractDependsOnBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private final Class<?> beanClass;
@@ -64,8 +63,7 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor
* @param dependsOn dependencies
* @since 2.0.4
*/
protected AbstractDependsOnBeanFactoryPostProcessor(Class<?> beanClass,
String... dependsOn) {
protected AbstractDependsOnBeanFactoryPostProcessor(Class<?> beanClass, String... dependsOn) {
this(beanClass, null, dependsOn);
}
@@ -83,28 +81,25 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor
private Iterable<String> getBeanNames(ListableBeanFactory beanFactory) {
Set<String> names = new HashSet<>();
names.addAll(Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
beanFactory, this.beanClass, true, false)));
names.addAll(Arrays
.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, this.beanClass, true, false)));
if (this.factoryBeanClass != null) {
for (String factoryBeanName : BeanFactoryUtils
.beanNamesForTypeIncludingAncestors(beanFactory,
this.factoryBeanClass, true, false)) {
for (String factoryBeanName : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
this.factoryBeanClass, true, false)) {
names.add(BeanFactoryUtils.transformedBeanName(factoryBeanName));
}
}
return names;
}
private static BeanDefinition getBeanDefinition(String beanName,
ConfigurableListableBeanFactory beanFactory) {
private static BeanDefinition getBeanDefinition(String beanName, ConfigurableListableBeanFactory beanFactory) {
try {
return beanFactory.getBeanDefinition(beanName);
}
catch (NoSuchBeanDefinitionException ex) {
BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
if (parentBeanFactory instanceof ConfigurableListableBeanFactory) {
return getBeanDefinition(beanName,
(ConfigurableListableBeanFactory) parentBeanFactory);
return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory);
}
throw ex;
}

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");
* you may not use this file except in compliance with the License.
@@ -44,25 +44,23 @@ public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoad
}
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader);
}
private boolean isConfiguration(MetadataReader metadataReader) {
return metadataReader.getAnnotationMetadata()
.isAnnotated(Configuration.class.getName());
return metadataReader.getAnnotationMetadata().isAnnotated(Configuration.class.getName());
}
private boolean isAutoConfiguration(MetadataReader metadataReader) {
return getAutoConfigurations()
.contains(metadataReader.getClassMetadata().getClassName());
return getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName());
}
protected List<String> getAutoConfigurations() {
if (this.autoConfigurations == null) {
this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames(
EnableAutoConfiguration.class, this.beanClassLoader);
this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,
this.beanClassLoader);
}
return this.autoConfigurations;
}

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");
* you may not use this file except in compliance with the License.
@@ -33,11 +33,9 @@ public class AutoConfigurationImportEvent extends EventObject {
private final Set<String> exclusions;
public AutoConfigurationImportEvent(Object source,
List<String> candidateConfigurations, Set<String> exclusions) {
public AutoConfigurationImportEvent(Object source, List<String> candidateConfigurations, Set<String> exclusions) {
super(source);
this.candidateConfigurations = Collections
.unmodifiableList(candidateConfigurations);
this.candidateConfigurations = Collections.unmodifiableList(candidateConfigurations);
this.exclusions = Collections.unmodifiableSet(exclusions);
}

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");
* you may not use this file except in compliance with the License.
@@ -54,7 +54,6 @@ public interface AutoConfigurationImportFilter {
* {@code autoConfigurationClasses} parameter. Entries containing {@code false} will
* not be imported.
*/
boolean[] match(String[] autoConfigurationClasses,
AutoConfigurationMetadata autoConfigurationMetadata);
boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata);
}

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");
* you may not use this file except in compliance with the License.
@@ -69,16 +69,14 @@ import org.springframework.util.StringUtils;
* @since 1.3.0
* @see EnableAutoConfiguration
*/
public class AutoConfigurationImportSelector
implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
BeanFactoryAware, EnvironmentAware, Ordered {
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
private static final AutoConfigurationEntry EMPTY_ENTRY = new AutoConfigurationEntry();
private static final String[] NO_IMPORTS = {};
private static final Log logger = LogFactory
.getLog(AutoConfigurationImportSelector.class);
private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.class);
private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
@@ -97,8 +95,8 @@ public class AutoConfigurationImportSelector
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(
autoConfigurationMetadata, annotationMetadata);
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
@@ -109,15 +107,13 @@ public class AutoConfigurationImportSelector
* @param annotationMetadata the annotation metadata of the configuration class
* @return the auto-configurations that should be imported
*/
protected AutoConfigurationEntry getAutoConfigurationEntry(
AutoConfigurationMetadata autoConfigurationMetadata,
protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
@@ -134,9 +130,7 @@ public class AutoConfigurationImportSelector
protected boolean isEnabled(AnnotationMetadata metadata) {
if (getClass() == AutoConfigurationImportSelector.class) {
return getEnvironment().getProperty(
EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class,
true);
return getEnvironment().getProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, true);
}
return true;
}
@@ -150,12 +144,9 @@ public class AutoConfigurationImportSelector
*/
protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
String name = getAnnotationClass().getName();
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(name, true));
Assert.notNull(attributes,
() -> "No auto-configuration attributes found. Is "
+ metadata.getClassName() + " annotated with "
+ ClassUtils.getShortName(name) + "?");
AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true));
Assert.notNull(attributes, () -> "No auto-configuration attributes found. Is " + metadata.getClassName()
+ " annotated with " + ClassUtils.getShortName(name) + "?");
return attributes;
}
@@ -176,13 +167,11 @@ public class AutoConfigurationImportSelector
* attributes}
* @return a list of candidate configurations
*/
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
Assert.notEmpty(configurations,
"No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
@@ -195,12 +184,10 @@ public class AutoConfigurationImportSelector
return EnableAutoConfiguration.class;
}
private void checkExcludedClasses(List<String> configurations,
Set<String> exclusions) {
private void checkExcludedClasses(List<String> configurations, Set<String> exclusions) {
List<String> invalidExcludes = new ArrayList<>(exclusions.size());
for (String exclusion : exclusions) {
if (ClassUtils.isPresent(exclusion, getClass().getClassLoader())
&& !configurations.contains(exclusion)) {
if (ClassUtils.isPresent(exclusion, getClass().getClassLoader()) && !configurations.contains(exclusion)) {
invalidExcludes.add(exclusion);
}
}
@@ -219,9 +206,9 @@ public class AutoConfigurationImportSelector
for (String exclude : invalidExcludes) {
message.append("\t- ").append(exclude).append(String.format("%n"));
}
throw new IllegalStateException(String
.format("The following classes could not be excluded because they are"
+ " not auto-configuration classes:%n%s", message));
throw new IllegalStateException(String.format(
"The following classes could not be excluded because they are" + " not auto-configuration classes:%n%s",
message));
}
/**
@@ -231,8 +218,7 @@ public class AutoConfigurationImportSelector
* attributes}
* @return exclusions or an empty set
*/
protected Set<String> getExclusions(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) {
Set<String> excluded = new LinkedHashSet<>();
excluded.addAll(asList(attributes, "exclude"));
excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName")));
@@ -243,16 +229,14 @@ public class AutoConfigurationImportSelector
private List<String> getExcludeAutoConfigurationsProperty() {
if (getEnvironment() instanceof ConfigurableEnvironment) {
Binder binder = Binder.get(getEnvironment());
return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class)
.map(Arrays::asList).orElse(Collections.emptyList());
return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(Arrays::asList)
.orElse(Collections.emptyList());
}
String[] excludes = getEnvironment()
.getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class);
String[] excludes = getEnvironment().getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class);
return (excludes != null) ? Arrays.asList(excludes) : Collections.emptyList();
}
private List<String> filter(List<String> configurations,
AutoConfigurationMetadata autoConfigurationMetadata) {
private List<String> filter(List<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata) {
long startTime = System.nanoTime();
String[] candidates = StringUtils.toStringArray(configurations);
boolean[] skip = new boolean[candidates.length];
@@ -280,15 +264,13 @@ public class AutoConfigurationImportSelector
if (logger.isTraceEnabled()) {
int numberFiltered = configurations.size() - result.size();
logger.trace("Filtered " + numberFiltered + " auto configuration class in "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)
+ " ms");
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + " ms");
}
return new ArrayList<>(result);
}
protected List<AutoConfigurationImportFilter> getAutoConfigurationImportFilters() {
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class,
this.beanClassLoader);
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader);
}
protected final <T> List<T> removeDuplicates(List<T> list) {
@@ -300,12 +282,10 @@ public class AutoConfigurationImportSelector
return Arrays.asList((value != null) ? value : new String[0]);
}
private void fireAutoConfigurationImportEvents(List<String> configurations,
Set<String> exclusions) {
private void fireAutoConfigurationImportEvents(List<String> configurations, Set<String> exclusions) {
List<AutoConfigurationImportListener> listeners = getAutoConfigurationImportListeners();
if (!listeners.isEmpty()) {
AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this,
configurations, exclusions);
AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, configurations, exclusions);
for (AutoConfigurationImportListener listener : listeners) {
invokeAwareMethods(listener);
listener.onAutoConfigurationImportEvent(event);
@@ -314,15 +294,13 @@ public class AutoConfigurationImportSelector
}
protected List<AutoConfigurationImportListener> getAutoConfigurationImportListeners() {
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class,
this.beanClassLoader);
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, this.beanClassLoader);
}
private void invokeAwareMethods(Object instance) {
if (instance instanceof Aware) {
if (instance instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) instance)
.setBeanClassLoader(this.beanClassLoader);
((BeanClassLoaderAware) instance).setBeanClassLoader(this.beanClassLoader);
}
if (instance instanceof BeanFactoryAware) {
((BeanFactoryAware) instance).setBeanFactory(this.beanFactory);
@@ -378,8 +356,8 @@ public class AutoConfigurationImportSelector
return Ordered.LOWEST_PRECEDENCE - 1;
}
private static class AutoConfigurationGroup implements DeferredImportSelector.Group,
BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware {
private static class AutoConfigurationGroup
implements DeferredImportSelector.Group, BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware {
private final Map<String, AnnotationMetadata> entries = new LinkedHashMap<>();
@@ -409,16 +387,13 @@ public class AutoConfigurationImportSelector
}
@Override
public void process(AnnotationMetadata annotationMetadata,
DeferredImportSelector deferredImportSelector) {
Assert.state(
deferredImportSelector instanceof AutoConfigurationImportSelector,
public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
() -> String.format("Only %s implementations are supported, got %s",
AutoConfigurationImportSelector.class.getSimpleName(),
deferredImportSelector.getClass().getName()));
AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
.getAutoConfigurationEntry(getAutoConfigurationMetadata(),
annotationMetadata);
.getAutoConfigurationEntry(getAutoConfigurationMetadata(), annotationMetadata);
this.autoConfigurationEntries.add(autoConfigurationEntry);
for (String importClassName : autoConfigurationEntry.getConfigurations()) {
this.entries.putIfAbsent(importClassName, annotationMetadata);
@@ -431,40 +406,33 @@ public class AutoConfigurationImportSelector
return Collections.emptyList();
}
Set<String> allExclusions = this.autoConfigurationEntries.stream()
.map(AutoConfigurationEntry::getExclusions)
.flatMap(Collection::stream).collect(Collectors.toSet());
.map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
Set<String> processedConfigurations = this.autoConfigurationEntries.stream()
.map(AutoConfigurationEntry::getConfigurations)
.flatMap(Collection::stream)
.map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream)
.collect(Collectors.toCollection(LinkedHashSet::new));
processedConfigurations.removeAll(allExclusions);
return sortAutoConfigurations(processedConfigurations,
getAutoConfigurationMetadata())
.stream()
.map((importClassName) -> new Entry(
this.entries.get(importClassName), importClassName))
.collect(Collectors.toList());
return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream()
.map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
.collect(Collectors.toList());
}
private AutoConfigurationMetadata getAutoConfigurationMetadata() {
if (this.autoConfigurationMetadata == null) {
this.autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
this.autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
}
return this.autoConfigurationMetadata;
}
private List<String> sortAutoConfigurations(Set<String> configurations,
AutoConfigurationMetadata autoConfigurationMetadata) {
return new AutoConfigurationSorter(getMetadataReaderFactory(),
autoConfigurationMetadata).getInPriorityOrder(configurations);
return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata)
.getInPriorityOrder(configurations);
}
private MetadataReaderFactory getMetadataReaderFactory() {
try {
return this.beanFactory.getBean(
SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
return this.beanFactory.getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
MetadataReaderFactory.class);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -491,8 +459,7 @@ public class AutoConfigurationImportSelector
* @param configurations the configurations that should be imported
* @param exclusions the exclusions that were applied to the original list
*/
AutoConfigurationEntry(Collection<String> configurations,
Collection<String> exclusions) {
AutoConfigurationEntry(Collection<String> configurations, Collection<String> exclusions) {
this.configurations = new ArrayList<>(configurations);
this.exclusions = new HashSet<>(exclusions);
}

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");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,7 @@ import org.springframework.util.StringUtils;
*/
final class AutoConfigurationMetadataLoader {
protected static final String PATH = "META-INF/"
+ "spring-autoconfigure-metadata.properties";
protected static final String PATH = "META-INF/" + "spring-autoconfigure-metadata.properties";
private AutoConfigurationMetadataLoader() {
}
@@ -49,14 +48,12 @@ final class AutoConfigurationMetadataLoader {
: ClassLoader.getSystemResources(path);
Properties properties = new Properties();
while (urls.hasMoreElements()) {
properties.putAll(PropertiesLoaderUtils
.loadProperties(new UrlResource(urls.nextElement())));
properties.putAll(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement())));
}
return loadMetadata(properties);
}
catch (IOException ex) {
throw new IllegalArgumentException(
"Unable to load @ConditionalOnClass location [" + path + "]", ex);
throw new IllegalArgumentException("Unable to load @ConditionalOnClass location [" + path + "]", ex);
}
}
@@ -67,8 +64,7 @@ final class AutoConfigurationMetadataLoader {
/**
* {@link AutoConfigurationMetadata} implementation backed by a properties file.
*/
private static class PropertiesAutoConfigurationMetadata
implements AutoConfigurationMetadata {
private static class PropertiesAutoConfigurationMetadata implements AutoConfigurationMetadata {
private final Properties properties;
@@ -98,11 +94,9 @@ final class AutoConfigurationMetadataLoader {
}
@Override
public Set<String> getSet(String className, String key,
Set<String> defaultValue) {
public Set<String> getSet(String className, String key, Set<String> defaultValue) {
String value = get(className, key);
return (value != null) ? StringUtils.commaDelimitedListToSet(value)
: defaultValue;
return (value != null) ? StringUtils.commaDelimitedListToSet(value) : defaultValue;
}
@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");
* you may not use this file except in compliance with the License.
@@ -73,8 +73,7 @@ public abstract class AutoConfigurationPackages {
return beanFactory.getBean(BEAN, BasePackages.class).get();
}
catch (NoSuchBeanDefinitionException ex) {
throw new IllegalStateException(
"Unable to retrieve @EnableAutoConfiguration base packages");
throw new IllegalStateException("Unable to retrieve @EnableAutoConfiguration base packages");
}
}
@@ -92,25 +91,20 @@ public abstract class AutoConfigurationPackages {
public static void register(BeanDefinitionRegistry registry, String... packageNames) {
if (registry.containsBeanDefinition(BEAN)) {
BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
ConstructorArgumentValues constructorArguments = beanDefinition
.getConstructorArgumentValues();
constructorArguments.addIndexedArgumentValue(0,
addBasePackages(constructorArguments, packageNames));
ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames));
}
else {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(BasePackages.class);
beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0,
packageNames);
beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(BEAN, beanDefinition);
}
}
private static String[] addBasePackages(
ConstructorArgumentValues constructorArguments, String[] packageNames) {
String[] existing = (String[]) constructorArguments
.getIndexedArgumentValue(0, String[].class).getValue();
private static String[] addBasePackages(ConstructorArgumentValues constructorArguments, String[] packageNames) {
String[] existing = (String[]) constructorArguments.getIndexedArgumentValue(0, String[].class).getValue();
Set<String> merged = new LinkedHashSet<>();
merged.addAll(Arrays.asList(existing));
merged.addAll(Arrays.asList(packageNames));
@@ -124,8 +118,7 @@ public abstract class AutoConfigurationPackages {
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
register(registry, new PackageImport(metadata).getPackageName());
}
@@ -201,12 +194,9 @@ public abstract class AutoConfigurationPackages {
}
else {
if (logger.isDebugEnabled()) {
String packageNames = StringUtils
.collectionToCommaDelimitedString(this.packages);
logger.debug("@EnableAutoConfiguration was declared on a class "
+ "in the package '" + packageNames
+ "'. Automatic @Repository and @Entity scanning is "
+ "enabled.");
String packageNames = StringUtils.collectionToCommaDelimitedString(this.packages);
logger.debug("@EnableAutoConfiguration was declared on a class " + "in the package '"
+ packageNames + "'. Automatic @Repository and @Entity scanning is " + "enabled.");
}
}
this.loggedBasePackageInfo = true;

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");
* you may not use this file except in compliance with the License.
@@ -52,8 +52,8 @@ class AutoConfigurationSorter {
}
public List<String> getInPriorityOrder(Collection<String> classNames) {
AutoConfigurationClasses classes = new AutoConfigurationClasses(
this.metadataReaderFactory, this.autoConfigurationMetadata, classNames);
AutoConfigurationClasses classes = new AutoConfigurationClasses(this.metadataReaderFactory,
this.autoConfigurationMetadata, classNames);
List<String> orderedClassNames = new ArrayList<>(classNames);
// Initially sort alphabetically
Collections.sort(orderedClassNames);
@@ -68,8 +68,7 @@ class AutoConfigurationSorter {
return orderedClassNames;
}
private List<String> sortByAnnotation(AutoConfigurationClasses classes,
List<String> classNames) {
private List<String> sortByAnnotation(AutoConfigurationClasses classes, List<String> classNames) {
List<String> toSort = new ArrayList<>(classNames);
toSort.addAll(classes.getAllNames());
Set<String> sorted = new LinkedHashSet<>();
@@ -81,9 +80,8 @@ class AutoConfigurationSorter {
return new ArrayList<>(sorted);
}
private void doSortByAfterAnnotation(AutoConfigurationClasses classes,
List<String> toSort, Set<String> sorted, Set<String> processing,
String current) {
private void doSortByAfterAnnotation(AutoConfigurationClasses classes, List<String> toSort, Set<String> sorted,
Set<String> processing, String current) {
if (current == null) {
current = toSort.remove(0);
}
@@ -104,10 +102,8 @@ class AutoConfigurationSorter {
private final Map<String, AutoConfigurationClass> classes = new HashMap<>();
AutoConfigurationClasses(MetadataReaderFactory metadataReaderFactory,
AutoConfigurationMetadata autoConfigurationMetadata,
Collection<String> classNames) {
addToClasses(metadataReaderFactory, autoConfigurationMetadata, classNames,
true);
AutoConfigurationMetadata autoConfigurationMetadata, Collection<String> classNames) {
addToClasses(metadataReaderFactory, autoConfigurationMetadata, classNames, true);
}
public Set<String> getAllNames() {
@@ -115,12 +111,11 @@ class AutoConfigurationSorter {
}
private void addToClasses(MetadataReaderFactory metadataReaderFactory,
AutoConfigurationMetadata autoConfigurationMetadata,
Collection<String> classNames, boolean required) {
AutoConfigurationMetadata autoConfigurationMetadata, Collection<String> classNames, boolean required) {
for (String className : classNames) {
if (!this.classes.containsKey(className)) {
AutoConfigurationClass autoConfigurationClass = new AutoConfigurationClass(
className, metadataReaderFactory, autoConfigurationMetadata);
AutoConfigurationClass autoConfigurationClass = new AutoConfigurationClass(className,
metadataReaderFactory, autoConfigurationMetadata);
boolean available = autoConfigurationClass.isAvailable();
if (required || available) {
this.classes.put(className, autoConfigurationClass);
@@ -166,8 +161,7 @@ class AutoConfigurationSorter {
private volatile Set<String> after;
AutoConfigurationClass(String className,
MetadataReaderFactory metadataReaderFactory,
AutoConfigurationClass(String className, MetadataReaderFactory metadataReaderFactory,
AutoConfigurationMetadata autoConfigurationMetadata) {
this.className = className;
this.metadataReaderFactory = metadataReaderFactory;
@@ -188,33 +182,28 @@ class AutoConfigurationSorter {
public Set<String> getBefore() {
if (this.before == null) {
this.before = (wasProcessed()
? this.autoConfigurationMetadata.getSet(this.className,
"AutoConfigureBefore", Collections.emptySet())
: getAnnotationValue(AutoConfigureBefore.class));
this.before = (wasProcessed() ? this.autoConfigurationMetadata.getSet(this.className,
"AutoConfigureBefore", Collections.emptySet()) : getAnnotationValue(AutoConfigureBefore.class));
}
return this.before;
}
public Set<String> getAfter() {
if (this.after == null) {
this.after = (wasProcessed()
? this.autoConfigurationMetadata.getSet(this.className,
"AutoConfigureAfter", Collections.emptySet())
: getAnnotationValue(AutoConfigureAfter.class));
this.after = (wasProcessed() ? this.autoConfigurationMetadata.getSet(this.className,
"AutoConfigureAfter", Collections.emptySet()) : getAnnotationValue(AutoConfigureAfter.class));
}
return this.after;
}
private int getOrder() {
if (wasProcessed()) {
return this.autoConfigurationMetadata.getInteger(this.className,
"AutoConfigureOrder", AutoConfigureOrder.DEFAULT_ORDER);
return this.autoConfigurationMetadata.getInteger(this.className, "AutoConfigureOrder",
AutoConfigureOrder.DEFAULT_ORDER);
}
Map<String, Object> attributes = getAnnotationMetadata()
.getAnnotationAttributes(AutoConfigureOrder.class.getName());
return (attributes != null) ? (Integer) attributes.get("value")
: AutoConfigureOrder.DEFAULT_ORDER;
return (attributes != null) ? (Integer) attributes.get("value") : AutoConfigureOrder.DEFAULT_ORDER;
}
private boolean wasProcessed() {
@@ -223,8 +212,8 @@ class AutoConfigurationSorter {
}
private Set<String> getAnnotationValue(Class<?> annotation) {
Map<String, Object> attributes = getAnnotationMetadata()
.getAnnotationAttributes(annotation.getName(), true);
Map<String, Object> attributes = getAnnotationMetadata().getAnnotationAttributes(annotation.getName(),
true);
if (attributes == null) {
return Collections.emptySet();
}
@@ -237,13 +226,11 @@ class AutoConfigurationSorter {
private AnnotationMetadata getAnnotationMetadata() {
if (this.annotationMetadata == null) {
try {
MetadataReader metadataReader = this.metadataReaderFactory
.getMetadataReader(this.className);
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(this.className);
this.annotationMetadata = metadataReader.getAnnotationMetadata();
}
catch (IOException ex) {
throw new IllegalStateException(
"Unable to read meta-data for class " + this.className, ex);
throw new IllegalStateException("Unable to read meta-data for class " + this.className, ex);
}
}
return this.annotationMetadata;

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");
* you may not use this file except in compliance with the License.
@@ -36,8 +36,8 @@ import org.springframework.util.ClassUtils;
*/
public class AutoConfigurations extends Configurations implements Ordered {
private static final AutoConfigurationSorter SORTER = new AutoConfigurationSorter(
new SimpleMetadataReaderFactory(), null);
private static final AutoConfigurationSorter SORTER = new AutoConfigurationSorter(new SimpleMetadataReaderFactory(),
null);
private static final Ordered ORDER = new AutoConfigurationImportSelector();
@@ -47,11 +47,9 @@ public class AutoConfigurations extends Configurations implements Ordered {
@Override
protected Collection<Class<?>> sort(Collection<Class<?>> classes) {
List<String> names = classes.stream().map(Class::getName)
.collect(Collectors.toList());
List<String> names = classes.stream().map(Class::getName).collect(Collectors.toList());
List<String> sorted = SORTER.getInPriorityOrder(names);
return sorted.stream()
.map((className) -> ClassUtils.resolveClassName(className, null))
return sorted.stream().map((className) -> ClassUtils.resolveClassName(className, null))
.collect(Collectors.toCollection(ArrayList::new));
}

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");
* you may not use this file except in compliance with the License.
@@ -50,8 +50,7 @@ import org.springframework.http.converter.support.AllEncompassingFormHttpMessage
* @since 1.3.0
*/
@Order(LoggingApplicationListener.DEFAULT_ORDER + 1)
public class BackgroundPreinitializer
implements ApplicationListener<SpringApplicationEvent> {
public class BackgroundPreinitializer implements ApplicationListener<SpringApplicationEvent> {
/**
* System property that instructs Spring Boot how to run pre initialization. When the
@@ -62,20 +61,17 @@ public class BackgroundPreinitializer
*/
public static final String IGNORE_BACKGROUNDPREINITIALIZER_PROPERTY_NAME = "spring.backgroundpreinitializer.ignore";
private static final AtomicBoolean preinitializationStarted = new AtomicBoolean(
false);
private static final AtomicBoolean preinitializationStarted = new AtomicBoolean(false);
private static final CountDownLatch preinitializationComplete = new CountDownLatch(1);
@Override
public void onApplicationEvent(SpringApplicationEvent event) {
if (!Boolean.getBoolean(IGNORE_BACKGROUNDPREINITIALIZER_PROPERTY_NAME)
&& event instanceof ApplicationStartingEvent
&& preinitializationStarted.compareAndSet(false, true)) {
&& event instanceof ApplicationStartingEvent && preinitializationStarted.compareAndSet(false, true)) {
performPreinitialization();
}
if ((event instanceof ApplicationReadyEvent
|| event instanceof ApplicationFailedEvent)
if ((event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent)
&& preinitializationStarted.get()) {
try {
preinitializationComplete.await();

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");
* you may not use this file except in compliance with the License.
@@ -44,8 +44,7 @@ import org.springframework.util.ObjectUtils;
* @author Phillip Webb
* @author Andy Wilkinson
*/
class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelector
implements DeterminableImports {
class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelector implements DeterminableImports {
private static final Set<String> ANNOTATION_NAMES;
@@ -70,26 +69,23 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec
}
@Override
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> candidates = new ArrayList<>();
Map<Class<?>, List<Annotation>> annotations = getAnnotations(metadata);
annotations.forEach((source, sourceAnnotations) -> collectCandidateConfigurations(
source, sourceAnnotations, candidates));
annotations.forEach(
(source, sourceAnnotations) -> collectCandidateConfigurations(source, sourceAnnotations, candidates));
return candidates;
}
private void collectCandidateConfigurations(Class<?> source,
List<Annotation> annotations, List<String> candidates) {
private void collectCandidateConfigurations(Class<?> source, List<Annotation> annotations,
List<String> candidates) {
for (Annotation annotation : annotations) {
candidates.addAll(getConfigurationsForAnnotation(source, annotation));
}
}
private Collection<String> getConfigurationsForAnnotation(Class<?> source,
Annotation annotation) {
String[] classes = (String[]) AnnotationUtils
.getAnnotationAttributes(annotation, true).get("classes");
private Collection<String> getConfigurationsForAnnotation(Class<?> source, Annotation annotation) {
String[] classes = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("classes");
if (classes.length > 0) {
return Arrays.asList(classes);
}
@@ -97,20 +93,16 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec
}
protected Collection<String> loadFactoryNames(Class<?> source) {
return SpringFactoriesLoader.loadFactoryNames(source,
getClass().getClassLoader());
return SpringFactoriesLoader.loadFactoryNames(source, getClass().getClassLoader());
}
@Override
protected Set<String> getExclusions(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) {
Set<String> exclusions = new LinkedHashSet<>();
Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), null);
for (String annotationName : ANNOTATION_NAMES) {
AnnotationAttributes merged = AnnotatedElementUtils
.getMergedAnnotationAttributes(source, annotationName);
Class<?>[] exclude = (merged != null) ? merged.getClassArray("exclude")
: null;
AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName);
Class<?>[] exclude = (merged != null) ? merged.getClassArray("exclude") : null;
if (exclude != null) {
for (Class<?> excludeClass : exclude) {
exclusions.add(excludeClass.getName());
@@ -119,8 +111,7 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec
}
for (List<Annotation> annotations : getAnnotations(metadata).values()) {
for (Annotation annotation : annotations) {
String[] exclude = (String[]) AnnotationUtils
.getAnnotationAttributes(annotation, true).get("exclude");
String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude");
if (!ObjectUtils.isEmpty(exclude)) {
exclusions.addAll(Arrays.asList(exclude));
}
@@ -129,21 +120,19 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec
return exclusions;
}
protected final Map<Class<?>, List<Annotation>> getAnnotations(
AnnotationMetadata metadata) {
protected final Map<Class<?>, List<Annotation>> getAnnotations(AnnotationMetadata metadata) {
MultiValueMap<Class<?>, Annotation> annotations = new LinkedMultiValueMap<>();
Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), null);
collectAnnotations(source, annotations, new HashSet<>());
return Collections.unmodifiableMap(annotations);
}
private void collectAnnotations(Class<?> source,
MultiValueMap<Class<?>, Annotation> annotations, HashSet<Class<?>> seen) {
private void collectAnnotations(Class<?> source, MultiValueMap<Class<?>, Annotation> annotations,
HashSet<Class<?>> seen) {
if (source != null && seen.add(source)) {
for (Annotation annotation : source.getDeclaredAnnotations()) {
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) {
if (ANNOTATION_NAMES
.contains(annotation.annotationType().getName())) {
if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) {
annotations.add(source, annotation);
}
collectAnnotations(annotation.annotationType(), annotations, seen);

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");
* you may not use this file except in compliance with the License.
@@ -46,16 +46,15 @@ import org.springframework.core.type.classreading.MetadataReaderFactory;
* @author Phillip Webb
* @since 1.4.0
*/
class SharedMetadataReaderFactoryContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
class SharedMetadataReaderFactoryContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
public static final String BEAN_NAME = "org.springframework.boot.autoconfigure."
+ "internalCachingMetadataReaderFactory";
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.addBeanFactoryPostProcessor(
new CachingMetadataReaderFactoryPostProcessor());
applicationContext.addBeanFactoryPostProcessor(new CachingMetadataReaderFactoryPostProcessor());
}
@Override
@@ -78,32 +77,27 @@ class SharedMetadataReaderFactoryContextInitializer implements
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
register(registry);
configureConfigurationClassPostProcessor(registry);
}
private void register(BeanDefinitionRegistry registry) {
BeanDefinition definition = BeanDefinitionBuilder
.genericBeanDefinition(SharedMetadataReaderFactoryBean.class,
SharedMetadataReaderFactoryBean::new)
.genericBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new)
.getBeanDefinition();
registry.registerBeanDefinition(BEAN_NAME, definition);
}
private void configureConfigurationClassPostProcessor(
BeanDefinitionRegistry registry) {
private void configureConfigurationClassPostProcessor(BeanDefinitionRegistry registry) {
try {
BeanDefinition definition = registry.getBeanDefinition(
AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME);
definition.getPropertyValues().add("metadataReaderFactory",
new RuntimeBeanReference(BEAN_NAME));
BeanDefinition definition = registry
.getBeanDefinition(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME);
definition.getPropertyValues().add("metadataReaderFactory", new RuntimeBeanReference(BEAN_NAME));
}
catch (NoSuchBeanDefinitionException ex) {
}
@@ -115,20 +109,18 @@ class SharedMetadataReaderFactoryContextInitializer implements
* {@link FactoryBean} to create the shared {@link MetadataReaderFactory}.
*/
static class SharedMetadataReaderFactoryBean
implements FactoryBean<ConcurrentReferenceCachingMetadataReaderFactory>,
BeanClassLoaderAware, ApplicationListener<ContextRefreshedEvent> {
implements FactoryBean<ConcurrentReferenceCachingMetadataReaderFactory>, BeanClassLoaderAware,
ApplicationListener<ContextRefreshedEvent> {
private ConcurrentReferenceCachingMetadataReaderFactory metadataReaderFactory;
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.metadataReaderFactory = new ConcurrentReferenceCachingMetadataReaderFactory(
classLoader);
this.metadataReaderFactory = new ConcurrentReferenceCachingMetadataReaderFactory(classLoader);
}
@Override
public ConcurrentReferenceCachingMetadataReaderFactory getObject()
throws Exception {
public ConcurrentReferenceCachingMetadataReaderFactory getObject() throws Exception {
return this.metadataReaderFactory;
}

View File

@@ -49,10 +49,8 @@ import org.springframework.core.annotation.AliasFor;
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM,
classes = AutoConfigurationExcludeFilter.class) })
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
/**

View File

@@ -41,8 +41,8 @@ import org.springframework.jmx.export.MBeanExporter;
*/
@Configuration
@AutoConfigureAfter(JmxAutoConfiguration.class)
@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled",
havingValue = "true", matchIfMissing = false)
@ConditionalOnProperty(prefix = "spring.application.admin", value = "enabled", havingValue = "true",
matchIfMissing = false)
public class SpringApplicationAdminJmxAutoConfiguration {
/**
@@ -60,18 +60,16 @@ public class SpringApplicationAdminJmxAutoConfiguration {
private final Environment environment;
public SpringApplicationAdminJmxAutoConfiguration(
ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) {
public SpringApplicationAdminJmxAutoConfiguration(ObjectProvider<MBeanExporter> mbeanExporters,
Environment environment) {
this.mbeanExporters = mbeanExporters;
this.environment = environment;
}
@Bean
@ConditionalOnMissingBean
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar()
throws MalformedObjectNameException {
String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY,
DEFAULT_JMX_NAME);
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar() throws MalformedObjectNameException {
String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME);
if (this.mbeanExporters != null) { // Make sure to not register that MBean twice
for (MBeanExporter mbeanExporter : this.mbeanExporters) {
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");
* you may not use this file except in compliance with the License.
@@ -68,8 +68,7 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer<T extends
* Set the {@link RabbitRetryTemplateCustomizer} instances to use.
* @param retryTemplateCustomizers the retry template customizers
*/
protected void setRetryTemplateCustomizers(
List<RabbitRetryTemplateCustomizer> retryTemplateCustomizers) {
protected void setRetryTemplateCustomizers(List<RabbitRetryTemplateCustomizer> retryTemplateCustomizers) {
this.retryTemplateCustomizers = retryTemplateCustomizers;
}
@@ -119,15 +118,13 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer<T extends
factory.setMissingQueuesFatal(configuration.isMissingQueuesFatal());
ListenerRetry retryConfig = configuration.getRetry();
if (retryConfig.isEnabled()) {
RetryInterceptorBuilder<?, ?> builder = (retryConfig.isStateless())
? RetryInterceptorBuilder.stateless()
RetryInterceptorBuilder<?, ?> builder = (retryConfig.isStateless()) ? RetryInterceptorBuilder.stateless()
: RetryInterceptorBuilder.stateful();
RetryTemplate retryTemplate = new RetryTemplateFactory(
this.retryTemplateCustomizers).createRetryTemplate(retryConfig,
RabbitRetryTemplateCustomizer.Target.LISTENER);
RetryTemplate retryTemplate = new RetryTemplateFactory(this.retryTemplateCustomizers)
.createRetryTemplate(retryConfig, RabbitRetryTemplateCustomizer.Target.LISTENER);
builder.retryOperations(retryTemplate);
MessageRecoverer recoverer = (this.messageRecoverer != null)
? this.messageRecoverer : new RejectAndDontRequeueRecoverer();
MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer
: new RejectAndDontRequeueRecoverer();
builder.recoverer(recoverer);
factory.setAdviceChain(builder.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");
* you may not use this file except in compliance with the License.
@@ -28,18 +28,15 @@ import org.springframework.boot.context.properties.PropertyMapper;
* @author Stephane Nicoll
* @since 2.0
*/
public final class DirectRabbitListenerContainerFactoryConfigurer extends
AbstractRabbitListenerContainerFactoryConfigurer<DirectRabbitListenerContainerFactory> {
public final class DirectRabbitListenerContainerFactoryConfigurer
extends AbstractRabbitListenerContainerFactoryConfigurer<DirectRabbitListenerContainerFactory> {
@Override
public void configure(DirectRabbitListenerContainerFactory factory,
ConnectionFactory connectionFactory) {
public void configure(DirectRabbitListenerContainerFactory factory, ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get();
RabbitProperties.DirectContainer config = getRabbitProperties().getListener()
.getDirect();
RabbitProperties.DirectContainer config = getRabbitProperties().getListener().getDirect();
configure(factory, connectionFactory, config);
map.from(config::getConsumersPerQueue).whenNonNull()
.to(factory::setConsumersPerQueue);
map.from(config::getConsumersPerQueue).whenNonNull().to(factory::setConsumersPerQueue);
}
}

View File

@@ -53,8 +53,7 @@ class RabbitAnnotationDrivenConfiguration {
RabbitAnnotationDrivenConfiguration(ObjectProvider<MessageConverter> messageConverter,
ObjectProvider<MessageRecoverer> messageRecoverer,
ObjectProvider<RabbitRetryTemplateCustomizer> retryTemplateCustomizers,
RabbitProperties properties) {
ObjectProvider<RabbitRetryTemplateCustomizer> retryTemplateCustomizers, RabbitProperties properties) {
this.messageConverter = messageConverter;
this.messageRecoverer = messageRecoverer;
this.retryTemplateCustomizers = retryTemplateCustomizers;
@@ -67,19 +66,18 @@ class RabbitAnnotationDrivenConfiguration {
SimpleRabbitListenerContainerFactoryConfigurer configurer = new SimpleRabbitListenerContainerFactoryConfigurer();
configurer.setMessageConverter(this.messageConverter.getIfUnique());
configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique());
configurer.setRetryTemplateCustomizers(this.retryTemplateCustomizers
.orderedStream().collect(Collectors.toList()));
configurer.setRetryTemplateCustomizers(
this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList()));
configurer.setRabbitProperties(this.properties);
return configurer;
}
@Bean(name = "rabbitListenerContainerFactory")
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type",
havingValue = "simple", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", havingValue = "simple",
matchIfMissing = true)
public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer,
ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
return factory;
@@ -91,19 +89,17 @@ class RabbitAnnotationDrivenConfiguration {
DirectRabbitListenerContainerFactoryConfigurer configurer = new DirectRabbitListenerContainerFactoryConfigurer();
configurer.setMessageConverter(this.messageConverter.getIfUnique());
configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique());
configurer.setRetryTemplateCustomizers(this.retryTemplateCustomizers
.orderedStream().collect(Collectors.toList()));
configurer.setRetryTemplateCustomizers(
this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList()));
configurer.setRabbitProperties(this.properties);
return configurer;
}
@Bean(name = "rabbitListenerContainerFactory")
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type",
havingValue = "direct")
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", havingValue = "direct")
public DirectRabbitListenerContainerFactory directRabbitListenerContainerFactory(
DirectRabbitListenerContainerFactoryConfigurer configurer,
ConnectionFactory connectionFactory) {
DirectRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
return factory;
@@ -111,8 +107,7 @@ class RabbitAnnotationDrivenConfiguration {
@Configuration
@EnableRabbit
@ConditionalOnMissingBean(
name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
@ConditionalOnMissingBean(name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
protected static class EnableRabbitConfiguration {
}

View File

@@ -92,10 +92,8 @@ public class RabbitAutoConfiguration {
protected static class RabbitConnectionFactoryCreator {
@Bean
public CachingConnectionFactory rabbitConnectionFactory(
RabbitProperties properties,
ObjectProvider<ConnectionNameStrategy> connectionNameStrategy)
throws Exception {
public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties properties,
ObjectProvider<ConnectionNameStrategy> connectionNameStrategy) throws Exception {
PropertyMapper map = PropertyMapper.get();
CachingConnectionFactory factory = new CachingConnectionFactory(
getRabbitConnectionFactoryBean(properties).getObject());
@@ -106,30 +104,24 @@ public class RabbitAutoConfiguration {
map.from(channel::getSize).whenNonNull().to(factory::setChannelCacheSize);
map.from(channel::getCheckoutTimeout).whenNonNull().as(Duration::toMillis)
.to(factory::setChannelCheckoutTimeout);
RabbitProperties.Cache.Connection connection = properties.getCache()
.getConnection();
RabbitProperties.Cache.Connection connection = properties.getCache().getConnection();
map.from(connection::getMode).whenNonNull().to(factory::setCacheMode);
map.from(connection::getSize).whenNonNull()
.to(factory::setConnectionCacheSize);
map.from(connectionNameStrategy::getIfUnique).whenNonNull()
.to(factory::setConnectionNameStrategy);
map.from(connection::getSize).whenNonNull().to(factory::setConnectionCacheSize);
map.from(connectionNameStrategy::getIfUnique).whenNonNull().to(factory::setConnectionNameStrategy);
return factory;
}
private RabbitConnectionFactoryBean getRabbitConnectionFactoryBean(
RabbitProperties properties) throws Exception {
private RabbitConnectionFactoryBean getRabbitConnectionFactoryBean(RabbitProperties properties)
throws Exception {
PropertyMapper map = PropertyMapper.get();
RabbitConnectionFactoryBean factory = new RabbitConnectionFactoryBean();
map.from(properties::determineHost).whenNonNull().to(factory::setHost);
map.from(properties::determinePort).to(factory::setPort);
map.from(properties::determineUsername).whenNonNull()
.to(factory::setUsername);
map.from(properties::determinePassword).whenNonNull()
.to(factory::setPassword);
map.from(properties::determineVirtualHost).whenNonNull()
.to(factory::setVirtualHost);
map.from(properties::getRequestedHeartbeat).whenNonNull()
.asInt(Duration::getSeconds).to(factory::setRequestedHeartbeat);
map.from(properties::determineUsername).whenNonNull().to(factory::setUsername);
map.from(properties::determinePassword).whenNonNull().to(factory::setPassword);
map.from(properties::determineVirtualHost).whenNonNull().to(factory::setVirtualHost);
map.from(properties::getRequestedHeartbeat).whenNonNull().asInt(Duration::getSeconds)
.to(factory::setRequestedHeartbeat);
RabbitProperties.Ssl ssl = properties.getSsl();
if (ssl.isEnabled()) {
factory.setUseSSL(true);
@@ -140,13 +132,12 @@ public class RabbitAutoConfiguration {
map.from(ssl::getTrustStoreType).to(factory::setTrustStoreType);
map.from(ssl::getTrustStore).to(factory::setTrustStore);
map.from(ssl::getTrustStorePassword).to(factory::setTrustStorePassphrase);
map.from(ssl::isValidateServerCertificate).to((validate) -> factory
.setSkipServerCertificateValidation(!validate));
map.from(ssl::getVerifyHostname)
.to(factory::setEnableHostnameVerification);
map.from(ssl::isValidateServerCertificate)
.to((validate) -> factory.setSkipServerCertificateValidation(!validate));
map.from(ssl::getVerifyHostname).to(factory::setEnableHostnameVerification);
}
map.from(properties::getConnectionTimeout).whenNonNull()
.asInt(Duration::toMillis).to(factory::setConnectionTimeout);
map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis)
.to(factory::setConnectionTimeout);
factory.afterPropertiesSet();
return factory;
}
@@ -185,19 +176,15 @@ public class RabbitAutoConfiguration {
RabbitProperties.Template properties = this.properties.getTemplate();
if (properties.getRetry().isEnabled()) {
template.setRetryTemplate(new RetryTemplateFactory(
this.retryTemplateCustomizers.orderedStream()
.collect(Collectors.toList())).createRetryTemplate(
properties.getRetry(),
RabbitRetryTemplateCustomizer.Target.SENDER));
this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())).createRetryTemplate(
properties.getRetry(), RabbitRetryTemplateCustomizer.Target.SENDER));
}
map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis)
.to(template::setReceiveTimeout);
map.from(properties::getReplyTimeout).whenNonNull().as(Duration::toMillis)
.to(template::setReplyTimeout);
map.from(properties::getReplyTimeout).whenNonNull().as(Duration::toMillis).to(template::setReplyTimeout);
map.from(properties::getExchange).to(template::setExchange);
map.from(properties::getRoutingKey).to(template::setRoutingKey);
map.from(properties::getDefaultReceiveQueue).whenNonNull()
.to(template::setDefaultReceiveQueue);
map.from(properties::getDefaultReceiveQueue).whenNonNull().to(template::setDefaultReceiveQueue);
return template;
}
@@ -208,8 +195,7 @@ public class RabbitAutoConfiguration {
@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
@ConditionalOnMissingBean
public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
@@ -225,8 +211,7 @@ public class RabbitAutoConfiguration {
@Bean
@ConditionalOnSingleCandidate(RabbitTemplate.class)
public RabbitMessagingTemplate rabbitMessagingTemplate(
RabbitTemplate rabbitTemplate) {
public RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) {
return new RabbitMessagingTemplate(rabbitTemplate);
}

View File

@@ -832,8 +832,7 @@ public class RabbitProperties {
}
@Deprecated
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.template.default-receive-queue")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.template.default-receive-queue")
public String getQueue() {
return getDefaultReceiveQueue();
}

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");
* you may not use this file except in compliance with the License.
@@ -49,8 +49,7 @@ class RetryTemplateFactory {
map.from(properties::getInitialInterval).whenNonNull().as(Duration::toMillis)
.to(backOffPolicy::setInitialInterval);
map.from(properties::getMultiplier).to(backOffPolicy::setMultiplier);
map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis)
.to(backOffPolicy::setMaxInterval);
map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis).to(backOffPolicy::setMaxInterval);
template.setBackOffPolicy(backOffPolicy);
if (this.customizers != null) {
for (RabbitRetryTemplateCustomizer customizer : this.customizers) {

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");
* you may not use this file except in compliance with the License.
@@ -28,20 +28,16 @@ import org.springframework.boot.context.properties.PropertyMapper;
* @author Gary Russell
* @since 1.3.3
*/
public final class SimpleRabbitListenerContainerFactoryConfigurer extends
AbstractRabbitListenerContainerFactoryConfigurer<SimpleRabbitListenerContainerFactory> {
public final class SimpleRabbitListenerContainerFactoryConfigurer
extends AbstractRabbitListenerContainerFactoryConfigurer<SimpleRabbitListenerContainerFactory> {
@Override
public void configure(SimpleRabbitListenerContainerFactory factory,
ConnectionFactory connectionFactory) {
public void configure(SimpleRabbitListenerContainerFactory factory, ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get();
RabbitProperties.SimpleContainer config = getRabbitProperties().getListener()
.getSimple();
RabbitProperties.SimpleContainer config = getRabbitProperties().getListener().getSimple();
configure(factory, connectionFactory, config);
map.from(config::getConcurrency).whenNonNull()
.to(factory::setConcurrentConsumers);
map.from(config::getMaxConcurrency).whenNonNull()
.to(factory::setMaxConcurrentConsumers);
map.from(config::getConcurrency).whenNonNull().to(factory::setConcurrentConsumers);
map.from(config::getMaxConcurrency).whenNonNull().to(factory::setMaxConcurrentConsumers);
map.from(config::getTransactionSize).whenNonNull().to(factory::setTxSize);
}

View File

@@ -40,24 +40,22 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy;
* @see EnableAspectJAutoProxy
*/
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class,
AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true",
matchIfMissing = true)
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class, AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class",
havingValue = "false", matchIfMissing = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
matchIfMissing = false)
public static class JdkDynamicAutoProxyConfiguration {
}
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
matchIfMissing = true)
public static class CglibAutoProxyConfiguration {
}

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");
* you may not use this file except in compliance with the License.
@@ -106,8 +106,7 @@ public class BasicBatchConfigurer implements BatchConfigurer {
PropertyMapper map = PropertyMapper.get();
JobExplorerFactoryBean factory = new JobExplorerFactoryBean();
factory.setDataSource(this.dataSource);
map.from(this.properties::getTablePrefix).whenHasText()
.to(factory::setTablePrefix);
map.from(this.properties::getTablePrefix).whenHasText().to(factory::setTablePrefix);
factory.afterPropertiesSet();
return factory.getObject();
}
@@ -123,10 +122,8 @@ public class BasicBatchConfigurer implements BatchConfigurer {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
PropertyMapper map = PropertyMapper.get();
map.from(this.dataSource).to(factory::setDataSource);
map.from(this::determineIsolationLevel).whenNonNull()
.to(factory::setIsolationLevelForCreate);
map.from(this.properties::getTablePrefix).whenHasText()
.to(factory::setTablePrefix);
map.from(this::determineIsolationLevel).whenNonNull().to(factory::setIsolationLevelForCreate);
map.from(this.properties::getTablePrefix).whenHasText().to(factory::setTablePrefix);
map.from(this::getTransactionManager).to(factory::setTransactionManager);
factory.afterPropertiesSet();
return factory.getObject();

View File

@@ -79,21 +79,16 @@ public class BatchAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(DataSource.class)
public BatchDataSourceInitializer batchDataSourceInitializer(DataSource dataSource,
ResourceLoader resourceLoader) {
return new BatchDataSourceInitializer(dataSource, resourceLoader,
this.properties);
public BatchDataSourceInitializer batchDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
return new BatchDataSourceInitializer(dataSource, resourceLoader, this.properties);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled",
havingValue = "true", matchIfMissing = true)
public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(
JobLauncher jobLauncher, JobExplorer jobExplorer,
@ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true)
public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer,
JobRepository jobRepository) {
JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(
jobLauncher, jobExplorer, jobRepository);
JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(jobLauncher, jobExplorer, jobRepository);
String jobNames = this.properties.getJob().getNames();
if (StringUtils.hasText(jobNames)) {
runner.setJobNames(jobNames);
@@ -110,8 +105,7 @@ public class BatchAutoConfiguration {
@Bean
@ConditionalOnMissingBean(JobOperator.class)
public SimpleJobOperator jobOperator(JobExplorer jobExplorer, JobLauncher jobLauncher,
ListableJobLocator jobRegistry, JobRepository jobRepository)
throws Exception {
ListableJobLocator jobRegistry, JobRepository jobRepository) throws Exception {
SimpleJobOperator factory = new SimpleJobOperator();
factory.setJobExplorer(jobExplorer);
factory.setJobLauncher(jobLauncher);

View File

@@ -44,11 +44,9 @@ class BatchConfigurerConfiguration {
static class JdbcBatchConfiguration {
@Bean
public BasicBatchConfigurer batchConfigurer(BatchProperties properties,
DataSource dataSource,
public BasicBatchConfigurer batchConfigurer(BatchProperties properties, DataSource dataSource,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
return new BasicBatchConfigurer(properties, dataSource,
transactionManagerCustomizers.getIfAvailable());
return new BasicBatchConfigurer(properties, dataSource, transactionManagerCustomizers.getIfAvailable());
}
}
@@ -59,12 +57,11 @@ class BatchConfigurerConfiguration {
static class JpaBatchConfiguration {
@Bean
public JpaBatchConfigurer batchConfigurer(BatchProperties properties,
DataSource dataSource,
public JpaBatchConfigurer batchConfigurer(BatchProperties properties, DataSource dataSource,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers,
EntityManagerFactory entityManagerFactory) {
return new JpaBatchConfigurer(properties, dataSource,
transactionManagerCustomizers.getIfAvailable(), entityManagerFactory);
return new JpaBatchConfigurer(properties, dataSource, transactionManagerCustomizers.getIfAvailable(),
entityManagerFactory);
}
}

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");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,8 @@ public class BatchDataSourceInitializer extends AbstractDataSourceInitializer {
private final BatchProperties properties;
public BatchDataSourceInitializer(DataSource dataSource,
ResourceLoader resourceLoader, BatchProperties properties) {
public BatchDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader,
BatchProperties properties) {
super(dataSource, resourceLoader);
Assert.notNull(properties, "BatchProperties must not be null");
this.properties = properties;

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");
* you may not use this file except in compliance with the License.
@@ -28,8 +28,7 @@ import org.springframework.context.ApplicationListener;
*
* @author Dave Syer
*/
public class JobExecutionExitCodeGenerator
implements ApplicationListener<JobExecutionEvent>, ExitCodeGenerator {
public class JobExecutionExitCodeGenerator implements ApplicationListener<JobExecutionEvent>, ExitCodeGenerator {
private final List<JobExecution> executions = new ArrayList<>();

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");
* you may not use this file except in compliance with the License.
@@ -64,16 +64,14 @@ import org.springframework.util.StringUtils;
* @author Jean-Pierre Bergamin
* @author Mahmoud Ben Hassine
*/
public class JobLauncherCommandLineRunner
implements CommandLineRunner, Ordered, ApplicationEventPublisherAware {
public class JobLauncherCommandLineRunner implements CommandLineRunner, Ordered, ApplicationEventPublisherAware {
/**
* The default order for the command line runner.
*/
public static final int DEFAULT_ORDER = 0;
private static final Log logger = LogFactory
.getLog(JobLauncherCommandLineRunner.class);
private static final Log logger = LogFactory.getLog(JobLauncherCommandLineRunner.class);
private JobParametersConverter converter = new DefaultJobParametersConverter();
@@ -103,8 +101,7 @@ public class JobLauncherCommandLineRunner
* parameters when running a job (which is not possible with the job explorer).
*/
@Deprecated
public JobLauncherCommandLineRunner(JobLauncher jobLauncher,
JobExplorer jobExplorer) {
public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) {
this.jobLauncher = jobLauncher;
this.jobExplorer = jobExplorer;
this.jobRepository = null;
@@ -117,8 +114,7 @@ public class JobLauncherCommandLineRunner
* @param jobRepository to check if a job instance exists with the given parameters
* when running a job
*/
public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer,
JobRepository jobRepository) {
public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, JobRepository jobRepository) {
Assert.notNull(jobLauncher, "JobLauncher must not be null");
Assert.notNull(jobExplorer, "JobExplorer must not be null");
Assert.notNull(jobRepository, "JobRepository must not be null");
@@ -166,15 +162,13 @@ public class JobLauncherCommandLineRunner
launchJobFromProperties(StringUtils.splitArrayElementsIntoProperties(args, "="));
}
protected void launchJobFromProperties(Properties properties)
throws JobExecutionException {
protected void launchJobFromProperties(Properties properties) throws JobExecutionException {
JobParameters jobParameters = this.converter.getJobParameters(properties);
executeLocalJobs(jobParameters);
executeRegisteredJobs(jobParameters);
}
private void executeLocalJobs(JobParameters jobParameters)
throws JobExecutionException {
private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException {
for (Job job : this.jobs) {
if (StringUtils.hasText(this.jobNames)) {
String[] jobsToRun = this.jobNames.split(",");
@@ -187,8 +181,7 @@ public class JobLauncherCommandLineRunner
}
}
private void executeRegisteredJobs(JobParameters jobParameters)
throws JobExecutionException {
private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException {
if (this.jobRegistry != null && StringUtils.hasText(this.jobNames)) {
String[] jobsToRun = this.jobNames.split(",");
for (String jobName : jobsToRun) {
@@ -207,9 +200,8 @@ public class JobLauncherCommandLineRunner
}
protected void execute(Job job, JobParameters jobParameters)
throws JobExecutionAlreadyRunningException, JobRestartException,
JobInstanceAlreadyCompleteException, JobParametersInvalidException,
JobParametersNotFoundException {
throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException, JobParametersNotFoundException {
JobParameters parameters = getNextJobParameters(job, jobParameters);
JobExecution execution = this.jobLauncher.run(job, parameters);
if (this.publisher != null) {
@@ -218,25 +210,21 @@ public class JobLauncherCommandLineRunner
}
private JobParameters getNextJobParameters(Job job, JobParameters jobParameters) {
if (this.jobRepository != null
&& this.jobRepository.isJobInstanceExists(job.getName(), jobParameters)) {
if (this.jobRepository != null && this.jobRepository.isJobInstanceExists(job.getName(), jobParameters)) {
return getNextJobParametersForExisting(job, jobParameters);
}
if (job.getJobParametersIncrementer() == null) {
return jobParameters;
}
JobParameters nextParameters = new JobParametersBuilder(jobParameters,
this.jobExplorer).getNextJobParameters(job).toJobParameters();
JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer)
.getNextJobParameters(job).toJobParameters();
return merge(nextParameters, jobParameters);
}
private JobParameters getNextJobParametersForExisting(Job job,
JobParameters jobParameters) {
JobExecution lastExecution = this.jobRepository.getLastJobExecution(job.getName(),
jobParameters);
private JobParameters getNextJobParametersForExisting(Job job, JobParameters jobParameters) {
JobExecution lastExecution = this.jobRepository.getLastJobExecution(job.getName(), jobParameters);
if (isStoppedOrFailed(lastExecution) && job.isRestartable()) {
JobParameters previousIdentifyingParameters = getGetIdentifying(
lastExecution.getJobParameters());
JobParameters previousIdentifyingParameters = getGetIdentifying(lastExecution.getJobParameters());
return merge(previousIdentifyingParameters, jobParameters);
}
return jobParameters;
@@ -248,8 +236,7 @@ public class JobLauncherCommandLineRunner
}
private JobParameters getGetIdentifying(JobParameters parameters) {
HashMap<String, JobParameter> nonIdentifying = new LinkedHashMap<>(
parameters.getParameters().size());
HashMap<String, JobParameter> nonIdentifying = new LinkedHashMap<>(parameters.getParameters().size());
parameters.getParameters().forEach((key, value) -> {
if (value.isIdentifying()) {
nonIdentifying.put(key, value);

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");
* you may not use this file except in compliance with the License.
@@ -46,16 +46,14 @@ public class JpaBatchConfigurer extends BasicBatchConfigurer {
* @param entityManagerFactory the entity manager factory (or {@code null})
*/
protected JpaBatchConfigurer(BatchProperties properties, DataSource dataSource,
TransactionManagerCustomizers transactionManagerCustomizers,
EntityManagerFactory entityManagerFactory) {
TransactionManagerCustomizers transactionManagerCustomizers, EntityManagerFactory entityManagerFactory) {
super(properties, dataSource, transactionManagerCustomizers);
this.entityManagerFactory = entityManagerFactory;
}
@Override
protected String determineIsolationLevel() {
logger.warn(
"JPA does not support custom isolation levels, so locks may not be taken when launching Jobs");
logger.warn("JPA does not support custom isolation levels, so locks may not be taken when launching Jobs");
return "ISOLATION_DEFAULT";
}

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");
* you may not use this file except in compliance with the License.
@@ -66,23 +66,20 @@ public class CacheAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public CacheManagerCustomizers cacheManagerCustomizers(
ObjectProvider<CacheManagerCustomizer<?>> customizers) {
return new CacheManagerCustomizers(
customizers.orderedStream().collect(Collectors.toList()));
public CacheManagerCustomizers cacheManagerCustomizers(ObjectProvider<CacheManagerCustomizer<?>> customizers) {
return new CacheManagerCustomizers(customizers.orderedStream().collect(Collectors.toList()));
}
@Bean
public CacheManagerValidator cacheAutoConfigurationValidator(
CacheProperties cacheProperties, ObjectProvider<CacheManager> cacheManager) {
public CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties,
ObjectProvider<CacheManager> cacheManager) {
return new CacheManagerValidator(cacheProperties, cacheManager);
}
@Configuration
@ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
@ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
protected static class CacheManagerJpaDependencyConfiguration
extends EntityManagerFactoryDependsOnPostProcessor {
protected static class CacheManagerJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor {
public CacheManagerJpaDependencyConfiguration() {
super("cacheManager");
@@ -100,8 +97,7 @@ public class CacheAutoConfiguration {
private final ObjectProvider<CacheManager> cacheManager;
CacheManagerValidator(CacheProperties cacheProperties,
ObjectProvider<CacheManager> cacheManager) {
CacheManagerValidator(CacheProperties cacheProperties, ObjectProvider<CacheManager> cacheManager) {
this.cacheProperties = cacheProperties;
this.cacheManager = cacheManager;
}
@@ -109,8 +105,7 @@ public class CacheAutoConfiguration {
@Override
public void afterPropertiesSet() {
Assert.notNull(this.cacheManager.getIfAvailable(),
() -> "No cache manager could "
+ "be auto-configured, check your configuration (caching "
() -> "No cache manager could " + "be auto-configured, check your configuration (caching "
+ "type is '" + this.cacheProperties.getType() + "')");
}

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");
* you may not use this file except in compliance with the License.
@@ -39,26 +39,21 @@ import org.springframework.core.type.ClassMetadata;
class CacheCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String sourceClass = "";
if (metadata instanceof ClassMetadata) {
sourceClass = ((ClassMetadata) metadata).getClassName();
}
ConditionMessage.Builder message = ConditionMessage.forCondition("Cache",
sourceClass);
ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", sourceClass);
Environment environment = context.getEnvironment();
try {
BindResult<CacheType> specified = Binder.get(environment)
.bind("spring.cache.type", CacheType.class);
BindResult<CacheType> specified = Binder.get(environment).bind("spring.cache.type", CacheType.class);
if (!specified.isBound()) {
return ConditionOutcome.match(message.because("automatic cache type"));
}
CacheType required = CacheConfigurations
.getType(((AnnotationMetadata) metadata).getClassName());
CacheType required = CacheConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
if (specified.get() == required) {
return ConditionOutcome
.match(message.because(specified.get() + " cache type"));
return ConditionOutcome.match(message.because(specified.get() + " cache type"));
}
}
catch (BindException ex) {

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");
* you may not use this file except in compliance with the License.
@@ -62,8 +62,7 @@ final class CacheConfigurations {
return entry.getKey();
}
}
throw new IllegalStateException(
"Unknown configuration class " + configurationClassName);
throw new IllegalStateException("Unknown configuration class " + configurationClassName);
}
}

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");
* you may not use this file except in compliance with the License.
@@ -34,10 +34,8 @@ public class CacheManagerCustomizers {
private final List<CacheManagerCustomizer<?>> customizers;
public CacheManagerCustomizers(
List<? extends CacheManagerCustomizer<?>> customizers) {
this.customizers = (customizers != null) ? new ArrayList<>(customizers)
: Collections.emptyList();
public CacheManagerCustomizers(List<? extends CacheManagerCustomizer<?>> customizers) {
this.customizers = (customizers != null) ? new ArrayList<>(customizers) : Collections.emptyList();
}
/**
@@ -51,8 +49,7 @@ public class CacheManagerCustomizers {
@SuppressWarnings("unchecked")
public <T extends CacheManager> T customize(T cacheManager) {
LambdaSafe.callbacks(CacheManagerCustomizer.class, this.customizers, cacheManager)
.withLogger(CacheManagerCustomizers.class)
.invoke((customizer) -> customizer.customize(cacheManager));
.withLogger(CacheManagerCustomizers.class).invoke((customizer) -> customizer.customize(cacheManager));
return 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");
* you may not use this file except in compliance with the License.
@@ -107,8 +107,8 @@ public class CacheProperties {
*/
public Resource resolveConfigLocation(Resource config) {
if (config != null) {
Assert.isTrue(config.exists(), () -> "Cache configuration does not exist '"
+ config.getDescription() + "'");
Assert.isTrue(config.exists(),
() -> "Cache configuration does not exist '" + config.getDescription() + "'");
return config;
}
return 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");
* you may not use this file except in compliance with the License.
@@ -55,10 +55,8 @@ class CaffeineCacheConfiguration {
private final CacheLoader<Object, Object> cacheLoader;
CaffeineCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers,
ObjectProvider<Caffeine<Object, Object>> caffeine,
ObjectProvider<CaffeineSpec> caffeineSpec,
CaffeineCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers,
ObjectProvider<Caffeine<Object, Object>> caffeine, ObjectProvider<CaffeineSpec> caffeineSpec,
ObjectProvider<CacheLoader<Object, Object>> cacheLoader) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;

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");
* you may not use this file except in compliance with the License.
@@ -53,8 +53,8 @@ public class CouchbaseCacheConfiguration {
private final Bucket bucket;
public CouchbaseCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers, Bucket bucket) {
public CouchbaseCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers,
Bucket bucket) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
this.bucket = bucket;
@@ -65,8 +65,8 @@ public class CouchbaseCacheConfiguration {
List<String> cacheNames = this.cacheProperties.getCacheNames();
CacheBuilder builder = CacheBuilder.newInstance(this.bucket);
Couchbase couchbase = this.cacheProperties.getCouchbase();
PropertyMapper.get().from(couchbase::getExpiration).whenNonNull()
.asInt(Duration::getSeconds).to(builder::withExpiration);
PropertyMapper.get().from(couchbase::getExpiration).whenNonNull().asInt(Duration::getSeconds)
.to(builder::withExpiration);
String[] names = StringUtils.toStringArray(cacheNames);
CouchbaseCacheManager cacheManager = new CouchbaseCacheManager(builder, names);
return this.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");
* you may not use this file except in compliance with the License.
@@ -41,16 +41,14 @@ import org.springframework.core.io.Resource;
@Configuration
@ConditionalOnClass({ Cache.class, EhCacheCacheManager.class })
@ConditionalOnMissingBean(org.springframework.cache.CacheManager.class)
@Conditional({ CacheCondition.class,
EhCacheCacheConfiguration.ConfigAvailableCondition.class })
@Conditional({ CacheCondition.class, EhCacheCacheConfiguration.ConfigAvailableCondition.class })
class EhCacheCacheConfiguration {
private final CacheProperties cacheProperties;
private final CacheManagerCustomizers customizers;
EhCacheCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers) {
EhCacheCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
}
@@ -63,8 +61,7 @@ class EhCacheCacheConfiguration {
@Bean
@ConditionalOnMissingBean
public CacheManager ehCacheCacheManager() {
Resource location = this.cacheProperties
.resolveConfigLocation(this.cacheProperties.getEhcache().getConfig());
Resource location = this.cacheProperties.resolveConfigLocation(this.cacheProperties.getEhcache().getConfig());
if (location != null) {
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");
* you may not use this file except in compliance with the License.
@@ -57,10 +57,8 @@ class HazelcastCacheConfiguration {
}
@Bean
public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance)
throws IOException {
HazelcastCacheManager cacheManager = new HazelcastCacheManager(
existingHazelcastInstance);
public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance) throws IOException {
HazelcastCacheManager cacheManager = new HazelcastCacheManager(existingHazelcastInstance);
return this.customizers.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");
* you may not use this file except in compliance with the License.
@@ -53,12 +53,10 @@ class HazelcastJCacheCustomizationConfiguration {
@Override
public void customize(CacheProperties cacheProperties, Properties properties) {
Resource configLocation = cacheProperties
.resolveConfigLocation(cacheProperties.getJcache().getConfig());
Resource configLocation = cacheProperties.resolveConfigLocation(cacheProperties.getJcache().getConfig());
if (configLocation != null) {
// Hazelcast does not use the URI as a mean to specify a custom config.
properties.setProperty("hazelcast.config.location",
toUri(configLocation).toString());
properties.setProperty("hazelcast.config.location", toUri(configLocation).toString());
}
else if (this.hazelcastInstance != null) {
properties.put("hazelcast.instance.itself", this.hazelcastInstance);
@@ -70,8 +68,7 @@ class HazelcastJCacheCustomizationConfiguration {
return config.getURI();
}
catch (IOException ex) {
throw new IllegalArgumentException("Could not get URI from " + config,
ex);
throw new IllegalArgumentException("Could not get URI from " + config, ex);
}
}

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");
* you may not use this file except in compliance with the License.
@@ -55,8 +55,7 @@ public class InfinispanCacheConfiguration {
private final ConfigurationBuilder defaultConfigurationBuilder;
public InfinispanCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers,
public InfinispanCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers,
ObjectProvider<ConfigurationBuilder> defaultConfigurationBuilder) {
this.cacheProperties = cacheProperties;
this.customizers = customizers;
@@ -64,10 +63,8 @@ public class InfinispanCacheConfiguration {
}
@Bean
public SpringEmbeddedCacheManager cacheManager(
EmbeddedCacheManager embeddedCacheManager) {
SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager(
embeddedCacheManager);
public SpringEmbeddedCacheManager cacheManager(EmbeddedCacheManager embeddedCacheManager) {
SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager(embeddedCacheManager);
return this.customizers.customize(cacheManager);
}
@@ -77,8 +74,8 @@ public class InfinispanCacheConfiguration {
EmbeddedCacheManager cacheManager = createEmbeddedCacheManager();
List<String> cacheNames = this.cacheProperties.getCacheNames();
if (!CollectionUtils.isEmpty(cacheNames)) {
cacheNames.forEach((cacheName) -> cacheManager.defineConfiguration(cacheName,
getDefaultCacheConfiguration()));
cacheNames.forEach(
(cacheName) -> cacheManager.defineConfiguration(cacheName, getDefaultCacheConfiguration()));
}
return 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");
* you may not use this file except in compliance with the License.
@@ -58,8 +58,7 @@ import org.springframework.util.StringUtils;
@Configuration
@ConditionalOnClass({ Caching.class, JCacheCacheManager.class })
@ConditionalOnMissingBean(org.springframework.cache.CacheManager.class)
@Conditional({ CacheCondition.class,
JCacheCacheConfiguration.JCacheAvailableCondition.class })
@Conditional({ CacheCondition.class, JCacheCacheConfiguration.JCacheAvailableCondition.class })
@Import(HazelcastJCacheCustomizationConfiguration.class)
class JCacheCacheConfiguration implements BeanClassLoaderAware {
@@ -75,8 +74,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware {
private ClassLoader beanClassLoader;
JCacheCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers,
JCacheCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers,
ObjectProvider<javax.cache.configuration.Configuration<?, ?>> defaultCacheConfiguration,
ObjectProvider<JCacheManagerCustomizer> cacheManagerCustomizers,
ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers) {
@@ -113,14 +111,12 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware {
}
private CacheManager createCacheManager() throws IOException {
CachingProvider cachingProvider = getCachingProvider(
this.cacheProperties.getJcache().getProvider());
CachingProvider cachingProvider = getCachingProvider(this.cacheProperties.getJcache().getProvider());
Properties properties = createCacheManagerProperties();
Resource configLocation = this.cacheProperties
.resolveConfigLocation(this.cacheProperties.getJcache().getConfig());
if (configLocation != null) {
return cachingProvider.getCacheManager(configLocation.getURI(),
this.beanClassLoader, properties);
return cachingProvider.getCacheManager(configLocation.getURI(), this.beanClassLoader, properties);
}
return cachingProvider.getCacheManager(null, this.beanClassLoader, properties);
}
@@ -134,8 +130,8 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware {
private Properties createCacheManagerProperties() {
Properties properties = new Properties();
this.cachePropertiesCustomizers.orderedStream().forEach(
(customizer) -> customizer.customize(this.cacheProperties, properties));
this.cachePropertiesCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(this.cacheProperties, properties));
return properties;
}
@@ -147,8 +143,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware {
}
private void customize(CacheManager cacheManager) {
this.cacheManagerCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(cacheManager));
this.cacheManagerCustomizers.orderedStream().forEach((customizer) -> customizer.customize(cacheManager));
}
/**
@@ -184,28 +179,22 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware {
static class JCacheProviderAvailableCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("JCache");
String providerProperty = "spring.cache.jcache.provider";
if (context.getEnvironment().containsProperty(providerProperty)) {
return ConditionOutcome
.match(message.because("JCache provider specified"));
return ConditionOutcome.match(message.because("JCache provider specified"));
}
Iterator<CachingProvider> providers = Caching.getCachingProviders()
.iterator();
Iterator<CachingProvider> providers = Caching.getCachingProviders().iterator();
if (!providers.hasNext()) {
return ConditionOutcome
.noMatch(message.didNotFind("JSR-107 provider").atAll());
return ConditionOutcome.noMatch(message.didNotFind("JSR-107 provider").atAll());
}
providers.next();
if (providers.hasNext()) {
return ConditionOutcome
.noMatch(message.foundExactly("multiple JSR-107 providers"));
return ConditionOutcome.noMatch(message.foundExactly("multiple JSR-107 providers"));
}
return ConditionOutcome
.match(message.foundExactly("single JSR-107 provider"));
return ConditionOutcome.match(message.foundExactly("single JSR-107 provider"));
}
}

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");
* you may not use this file except in compliance with the License.
@@ -59,8 +59,7 @@ class RedisCacheConfiguration {
private final org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration;
RedisCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizerInvoker,
RedisCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker,
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration) {
this.cacheProperties = cacheProperties;
this.customizerInvoker = customizerInvoker;
@@ -70,8 +69,7 @@ class RedisCacheConfiguration {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory,
ResourceLoader resourceLoader) {
RedisCacheManagerBuilder builder = RedisCacheManager
.builder(redisConnectionFactory)
RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(determineConfiguration(resourceLoader.getClassLoader()));
List<String> cacheNames = this.cacheProperties.getCacheNames();
if (!cacheNames.isEmpty()) {
@@ -88,8 +86,8 @@ class RedisCacheConfiguration {
Redis redisProperties = this.cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig();
config = config.serializeValuesWith(SerializationPair
.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
config = config.serializeValuesWith(
SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}

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");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ class SimpleCacheConfiguration {
private final CacheManagerCustomizers customizerInvoker;
SimpleCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizerInvoker) {
SimpleCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker) {
this.cacheProperties = cacheProperties;
this.customizerInvoker = customizerInvoker;
}

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");
* you may not use this file except in compliance with the License.
@@ -64,43 +64,36 @@ public class CassandraAutoConfiguration {
public Cluster cassandraCluster() {
PropertyMapper map = PropertyMapper.get();
CassandraProperties properties = this.properties;
Cluster.Builder builder = Cluster.builder()
.withClusterName(properties.getClusterName())
Cluster.Builder builder = Cluster.builder().withClusterName(properties.getClusterName())
.withPort(properties.getPort());
map.from(properties::getUsername).whenNonNull().to((username) -> builder
.withCredentials(username, properties.getPassword()));
map.from(properties::getUsername).whenNonNull()
.to((username) -> builder.withCredentials(username, properties.getPassword()));
map.from(properties::getCompression).whenNonNull().to(builder::withCompression);
map.from(properties::getLoadBalancingPolicy).whenNonNull()
.as(BeanUtils::instantiateClass).to(builder::withLoadBalancingPolicy);
map.from(properties::getLoadBalancingPolicy).whenNonNull().as(BeanUtils::instantiateClass)
.to(builder::withLoadBalancingPolicy);
map.from(this::getQueryOptions).to(builder::withQueryOptions);
map.from(properties::getReconnectionPolicy).whenNonNull()
.as(BeanUtils::instantiateClass).to(builder::withReconnectionPolicy);
map.from(properties::getRetryPolicy).whenNonNull().as(BeanUtils::instantiateClass)
.to(builder::withRetryPolicy);
map.from(properties::getReconnectionPolicy).whenNonNull().as(BeanUtils::instantiateClass)
.to(builder::withReconnectionPolicy);
map.from(properties::getRetryPolicy).whenNonNull().as(BeanUtils::instantiateClass).to(builder::withRetryPolicy);
map.from(this::getSocketOptions).to(builder::withSocketOptions);
map.from(properties::isSsl).whenTrue().toCall(builder::withSSL);
map.from(this::getPoolingOptions).to(builder::withPoolingOptions);
map.from(properties::getContactPoints).as(StringUtils::toStringArray)
.to(builder::addContactPoints);
map.from(properties::isJmxEnabled).whenFalse()
.toCall(builder::withoutJMXReporting);
map.from(properties::getContactPoints).as(StringUtils::toStringArray).to(builder::addContactPoints);
map.from(properties::isJmxEnabled).whenFalse().toCall(builder::withoutJMXReporting);
customize(builder);
return builder.build();
}
private void customize(Cluster.Builder builder) {
this.builderCustomizers.orderedStream()
.forEach((customizer) -> customizer.customize(builder));
this.builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
}
private QueryOptions getQueryOptions() {
PropertyMapper map = PropertyMapper.get();
QueryOptions options = new QueryOptions();
CassandraProperties properties = this.properties;
map.from(properties::getConsistencyLevel).whenNonNull()
.to(options::setConsistencyLevel);
map.from(properties::getSerialConsistencyLevel).whenNonNull()
.to(options::setSerialConsistencyLevel);
map.from(properties::getConsistencyLevel).whenNonNull().to(options::setConsistencyLevel);
map.from(properties::getSerialConsistencyLevel).whenNonNull().to(options::setSerialConsistencyLevel);
map.from(properties::getFetchSize).to(options::setFetchSize);
return options;
}
@@ -108,8 +101,8 @@ public class CassandraAutoConfiguration {
private SocketOptions getSocketOptions() {
PropertyMapper map = PropertyMapper.get();
SocketOptions options = new SocketOptions();
map.from(this.properties::getConnectTimeout).whenNonNull()
.asInt(Duration::toMillis).to(options::setConnectTimeoutMillis);
map.from(this.properties::getConnectTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setConnectTimeoutMillis);
map.from(this.properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setReadTimeoutMillis);
return options;
@@ -121,10 +114,9 @@ public class CassandraAutoConfiguration {
PoolingOptions options = new PoolingOptions();
map.from(properties::getIdleTimeout).whenNonNull().asInt(Duration::getSeconds)
.to(options::setIdleTimeoutSeconds);
map.from(properties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis)
.to(options::setPoolTimeoutMillis);
map.from(properties::getHeartbeatInterval).whenNonNull()
.asInt(Duration::getSeconds).to(options::setHeartbeatIntervalSeconds);
map.from(properties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis).to(options::setPoolTimeoutMillis);
map.from(properties::getHeartbeatInterval).whenNonNull().asInt(Duration::getSeconds)
.to(options::setHeartbeatIntervalSeconds);
map.from(properties::getMaxQueueSize).to(options::setMaxQueueSize);
return options;
}

View File

@@ -59,8 +59,7 @@ public class CassandraProperties {
/**
* Cluster node addresses.
*/
private final List<String> contactPoints = new ArrayList<>(
Collections.singleton("localhost"));
private final List<String> contactPoints = new ArrayList<>(Collections.singleton("localhost"));
/**
* Port of the Cassandra server.
@@ -195,16 +194,14 @@ public class CassandraProperties {
this.compression = compression;
}
@DeprecatedConfigurationProperty(
reason = "Implement a ClusterBuilderCustomizer bean instead.")
@DeprecatedConfigurationProperty(reason = "Implement a ClusterBuilderCustomizer bean instead.")
@Deprecated
public Class<? extends LoadBalancingPolicy> getLoadBalancingPolicy() {
return this.loadBalancingPolicy;
}
@Deprecated
public void setLoadBalancingPolicy(
Class<? extends LoadBalancingPolicy> loadBalancingPolicy) {
public void setLoadBalancingPolicy(Class<? extends LoadBalancingPolicy> loadBalancingPolicy) {
this.loadBalancingPolicy = loadBalancingPolicy;
}
@@ -232,21 +229,18 @@ public class CassandraProperties {
this.fetchSize = fetchSize;
}
@DeprecatedConfigurationProperty(
reason = "Implement a ClusterBuilderCustomizer bean instead.")
@DeprecatedConfigurationProperty(reason = "Implement a ClusterBuilderCustomizer bean instead.")
@Deprecated
public Class<? extends ReconnectionPolicy> getReconnectionPolicy() {
return this.reconnectionPolicy;
}
@Deprecated
public void setReconnectionPolicy(
Class<? extends ReconnectionPolicy> reconnectionPolicy) {
public void setReconnectionPolicy(Class<? extends ReconnectionPolicy> reconnectionPolicy) {
this.reconnectionPolicy = reconnectionPolicy;
}
@DeprecatedConfigurationProperty(
reason = "Implement a ClusterBuilderCustomizer bean instead.")
@DeprecatedConfigurationProperty(reason = "Implement a ClusterBuilderCustomizer bean instead.")
@Deprecated
public Class<? extends RetryPolicy> getRetryPolicy() {
return this.retryPolicy;

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");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,7 @@ import org.springframework.util.MultiValueMap;
* @author Phillip Webb
* @since 2.0.1
*/
public abstract class AbstractNestedCondition extends SpringBootCondition
implements ConfigurationCondition {
public abstract class AbstractNestedCondition extends SpringBootCondition implements ConfigurationCondition {
private final ConfigurationPhase configurationPhase;
@@ -58,16 +57,14 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String className = getClass().getName();
MemberConditions memberConditions = new MemberConditions(context, className);
MemberMatchOutcomes memberOutcomes = new MemberMatchOutcomes(memberConditions);
return getFinalMatchOutcome(memberOutcomes);
}
protected abstract ConditionOutcome getFinalMatchOutcome(
MemberMatchOutcomes memberOutcomes);
protected abstract ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes);
protected static class MemberMatchOutcomes {
@@ -112,14 +109,12 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
MemberConditions(ConditionContext context, String className) {
this.context = context;
this.readerFactory = new SimpleMetadataReaderFactory(
context.getResourceLoader());
this.readerFactory = new SimpleMetadataReaderFactory(context.getResourceLoader());
String[] members = getMetadata(className).getMemberClassNames();
this.memberConditions = getMemberConditions(members);
}
private Map<AnnotationMetadata, List<Condition>> getMemberConditions(
String[] members) {
private Map<AnnotationMetadata, List<Condition>> getMemberConditions(String[] members) {
MultiValueMap<AnnotationMetadata, Condition> memberConditions = new LinkedMultiValueMap<>();
for (String member : members) {
AnnotationMetadata metadata = getMetadata(member);
@@ -135,8 +130,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
private AnnotationMetadata getMetadata(String className) {
try {
return this.readerFactory.getMetadataReader(className)
.getAnnotationMetadata();
return this.readerFactory.getMetadataReader(className).getAnnotationMetadata();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
@@ -145,23 +139,21 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
@SuppressWarnings("unchecked")
private List<String[]> getConditionClasses(AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(Conditional.class.getName(), true);
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(Conditional.class.getName(),
true);
Object values = (attributes != null) ? attributes.get("value") : null;
return (List<String[]>) ((values != null) ? values : Collections.emptyList());
}
private Condition getCondition(String conditionClassName) {
Class<?> conditionClass = ClassUtils.resolveClassName(conditionClassName,
this.context.getClassLoader());
Class<?> conditionClass = ClassUtils.resolveClassName(conditionClassName, this.context.getClassLoader());
return (Condition) BeanUtils.instantiateClass(conditionClass);
}
public List<ConditionOutcome> getMatchOutcomes() {
List<ConditionOutcome> outcomes = new ArrayList<>();
this.memberConditions.forEach((metadata, conditions) -> outcomes
.add(new MemberOutcomes(this.context, metadata, conditions)
.getUltimateOutcome()));
.add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome()));
return Collections.unmodifiableList(outcomes);
}
@@ -175,8 +167,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
private final List<ConditionOutcome> outcomes;
MemberOutcomes(ConditionContext context, AnnotationMetadata metadata,
List<Condition> conditions) {
MemberOutcomes(ConditionContext context, AnnotationMetadata metadata, List<Condition> conditions) {
this.context = context;
this.metadata = metadata;
this.outcomes = new ArrayList<>(conditions.size());
@@ -185,24 +176,19 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
}
}
private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata,
Condition condition) {
private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata, Condition condition) {
if (condition instanceof SpringBootCondition) {
return ((SpringBootCondition) condition).getMatchOutcome(this.context,
metadata);
return ((SpringBootCondition) condition).getMatchOutcome(this.context, metadata);
}
return new ConditionOutcome(condition.matches(this.context, metadata),
ConditionMessage.empty());
return new ConditionOutcome(condition.matches(this.context, metadata), ConditionMessage.empty());
}
public ConditionOutcome getUltimateOutcome() {
ConditionMessage.Builder message = ConditionMessage
.forCondition("NestedCondition on "
+ ClassUtils.getShortName(this.metadata.getClassName()));
.forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName()));
if (this.outcomes.size() == 1) {
ConditionOutcome outcome = this.outcomes.get(0);
return new ConditionOutcome(outcome.isMatch(),
message.because(outcome.getMessage()));
return new ConditionOutcome(outcome.isMatch(), message.because(outcome.getMessage()));
}
List<ConditionOutcome> match = new ArrayList<>();
List<ConditionOutcome> nonMatch = new ArrayList<>();
@@ -210,11 +196,9 @@ public abstract class AbstractNestedCondition extends SpringBootCondition
(outcome.isMatch() ? match : nonMatch).add(outcome);
}
if (nonMatch.isEmpty()) {
return ConditionOutcome
.match(message.found("matching nested conditions").items(match));
return ConditionOutcome.match(message.found("matching nested conditions").items(match));
}
return ConditionOutcome.noMatch(
message.found("non-matching nested conditions").items(nonMatch));
return ConditionOutcome.noMatch(message.found("non-matching nested conditions").items(nonMatch));
}
}

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");
* you may not use this file except in compliance with the License.
@@ -62,9 +62,8 @@ public abstract class AllNestedConditions extends AbstractNestedCondition {
protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) {
boolean match = hasSameSize(memberOutcomes.getMatches(), memberOutcomes.getAll());
List<ConditionMessage> messages = new ArrayList<>();
messages.add(ConditionMessage.forCondition("AllNestedConditions")
.because(memberOutcomes.getMatches().size() + " matched "
+ memberOutcomes.getNonMatches().size() + " did not"));
messages.add(ConditionMessage.forCondition("AllNestedConditions").because(
memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not"));
for (ConditionOutcome outcome : memberOutcomes.getAll()) {
messages.add(outcome.getConditionMessage());
}

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");
* you may not use this file except in compliance with the License.
@@ -65,9 +65,8 @@ public abstract class AnyNestedCondition extends AbstractNestedCondition {
protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) {
boolean match = !memberOutcomes.getMatches().isEmpty();
List<ConditionMessage> messages = new ArrayList<>();
messages.add(ConditionMessage.forCondition("AnyNestedCondition")
.because(memberOutcomes.getMatches().size() + " matched "
+ memberOutcomes.getNonMatches().size() + " did not"));
messages.add(ConditionMessage.forCondition("AnyNestedCondition").because(
memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not"));
for (ConditionOutcome outcome : memberOutcomes.getAll()) {
messages.add(outcome.getConditionMessage());
}

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");
* you may not use this file except in compliance with the License.
@@ -117,10 +117,9 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
public Set<String> getNamesForAnnotation(Class<? extends Annotation> annotation) {
updateTypesIfNecessary();
return this.beanTypes.entrySet().stream()
.filter((entry) -> entry.getValue() != null && AnnotationUtils
.findAnnotation(entry.getValue().resolve(), annotation) != null)
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
.filter((entry) -> entry.getValue() != null
&& AnnotationUtils.findAnnotation(entry.getValue().resolve(), annotation) != null)
.map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new));
}
@Override
@@ -131,8 +130,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
}
private void updateTypesIfNecessary() {
this.beanFactory.getBeanNamesIterator()
.forEachRemaining(this::updateTypesIfNecessary);
this.beanFactory.getBeanNamesIterator().forEachRemaining(this::updateTypesIfNecessary);
}
private void updateTypesIfNecessary(String name) {
@@ -184,20 +182,16 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
}
}
private void addBeanTypeForNonAliasDefinition(String name,
RootBeanDefinition definition) {
private void addBeanTypeForNonAliasDefinition(String name, RootBeanDefinition definition) {
try {
if (!definition.isAbstract()
&& !requiresEagerInit(definition.getFactoryBeanName())) {
ResolvableType factoryMethodReturnType = getFactoryMethodReturnType(
definition);
if (!definition.isAbstract() && !requiresEagerInit(definition.getFactoryBeanName())) {
ResolvableType factoryMethodReturnType = getFactoryMethodReturnType(definition);
String factoryBeanName = BeanFactory.FACTORY_BEAN_PREFIX + name;
if (this.beanFactory.isFactoryBean(factoryBeanName)) {
ResolvableType factoryBeanGeneric = getFactoryBeanGeneric(
this.beanFactory, definition, factoryMethodReturnType);
ResolvableType factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, definition,
factoryMethodReturnType);
this.beanTypes.put(name, factoryBeanGeneric);
this.beanTypes.put(factoryBeanName,
getType(factoryBeanName, factoryMethodReturnType));
this.beanTypes.put(factoryBeanName, getType(factoryBeanName, factoryMethodReturnType));
}
else {
this.beanTypes.put(name, getType(name, factoryMethodReturnType));
@@ -221,8 +215,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
if (StringUtils.hasLength(definition.getFactoryBeanName())
&& StringUtils.hasLength(definition.getFactoryMethodName())) {
Method method = getFactoryMethod(this.beanFactory, definition);
ResolvableType type = (method != null)
? ResolvableType.forMethodReturnType(method) : null;
ResolvableType type = (method != null) ? ResolvableType.forMethodReturnType(method) : null;
return type;
}
}
@@ -231,18 +224,15 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
return null;
}
private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory,
BeanDefinition definition) throws Exception {
private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
throws Exception {
if (definition instanceof AnnotatedBeanDefinition) {
MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition)
.getFactoryMethodMetadata();
MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata();
if (factoryMethodMetadata instanceof StandardMethodMetadata) {
return ((StandardMethodMetadata) factoryMethodMetadata)
.getIntrospectedMethod();
return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod();
}
}
BeanDefinition factoryDefinition = beanFactory
.getBeanDefinition(definition.getFactoryBeanName());
BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName());
Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(),
beanFactory.getBeanClassLoader());
return getFactoryMethod(definition, factoryClass);
@@ -263,10 +253,8 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
return uniqueMethod;
}
private Method[] getCandidateFactoryMethods(BeanDefinition definition,
Class<?> factoryClass) {
return (shouldConsiderNonPublicMethods(definition)
? ReflectionUtils.getAllDeclaredMethods(factoryClass)
private Method[] getCandidateFactoryMethods(BeanDefinition definition, Class<?> factoryClass) {
return (shouldConsiderNonPublicMethods(definition) ? ReflectionUtils.getAllDeclaredMethods(factoryClass)
: factoryClass.getMethods());
}
@@ -293,8 +281,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
* @param factoryMethodReturnType the factory method return type
* @return the generic type of the {@link FactoryBean} or {@code null}
*/
private ResolvableType getFactoryBeanGeneric(
ConfigurableListableBeanFactory beanFactory, BeanDefinition definition,
private ResolvableType getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition,
ResolvableType factoryMethodReturnType) {
try {
if (factoryMethodReturnType != null) {
@@ -309,27 +296,23 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
return null;
}
private ResolvableType getDirectFactoryBeanGeneric(
ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
throws ClassNotFoundException, LinkageError {
Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(),
beanFactory.getBeanClassLoader());
private ResolvableType getDirectFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory,
BeanDefinition definition) throws ClassNotFoundException, LinkageError {
Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader());
return getFactoryBeanType(definition, ResolvableType.forClass(factoryBeanClass));
}
private ResolvableType getFactoryBeanType(BeanDefinition definition,
ResolvableType type) throws ClassNotFoundException, LinkageError {
private ResolvableType getFactoryBeanType(BeanDefinition definition, ResolvableType type)
throws ClassNotFoundException, LinkageError {
ResolvableType generic = type.as(FactoryBean.class).getGeneric();
if ((generic == null || generic.resolve().equals(Object.class))
&& definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(
definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
}
return generic;
}
private ResolvableType getTypeFromAttribute(Object attribute)
throws ClassNotFoundException, LinkageError {
private ResolvableType getTypeFromAttribute(Object attribute) throws ClassNotFoundException, LinkageError {
if (attribute instanceof Class<?>) {
return ResolvableType.forClass((Class<?>) attribute);
}
@@ -340,8 +323,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
}
private ResolvableType getType(String name, ResolvableType factoryMethodReturnType) {
if (factoryMethodReturnType != null
&& !factoryMethodReturnType.resolve(Object.class).equals(Object.class)) {
if (factoryMethodReturnType != null && !factoryMethodReturnType.resolve(Object.class).equals(Object.class)) {
return factoryMethodReturnType;
}
Class<?> type = this.beanFactory.getType(name);
@@ -356,14 +338,10 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
static BeanTypeRegistry get(ListableBeanFactory beanFactory) {
Assert.isInstanceOf(DefaultListableBeanFactory.class, beanFactory);
DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
Assert.isTrue(listableBeanFactory.isAllowEagerClassLoading(),
"Bean factory must allow eager class loading");
Assert.isTrue(listableBeanFactory.isAllowEagerClassLoading(), "Bean factory must allow eager class loading");
if (!listableBeanFactory.containsLocalBean(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.genericBeanDefinition(BeanTypeRegistry.class,
() -> new BeanTypeRegistry(
(DefaultListableBeanFactory) beanFactory))
.getBeanDefinition();
BeanDefinition definition = BeanDefinitionBuilder.genericBeanDefinition(BeanTypeRegistry.class,
() -> new BeanTypeRegistry((DefaultListableBeanFactory) beanFactory)).getBeanDefinition();
listableBeanFactory.registerBeanDefinition(BEAN_NAME, definition);
}
return listableBeanFactory.getBean(BEAN_NAME, BeanTypeRegistry.class);

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");
* you may not use this file except in compliance with the License.
@@ -75,8 +75,7 @@ public final class ConditionEvaluationReport {
* @param condition the condition evaluated
* @param outcome the condition outcome
*/
public void recordConditionEvaluation(String source, Condition condition,
ConditionOutcome outcome) {
public void recordConditionEvaluation(String source, Condition condition, ConditionOutcome outcome) {
Assert.notNull(source, "Source must not be null");
Assert.notNull(condition, "Condition must not be null");
Assert.notNull(outcome, "Outcome must not be null");
@@ -127,8 +126,8 @@ public final class ConditionEvaluationReport {
String prefix = source + "$";
this.outcomes.forEach((candidateSource, sourceOutcomes) -> {
if (candidateSource.startsWith(prefix)) {
ConditionOutcome outcome = ConditionOutcome.noMatch(ConditionMessage
.forCondition("Ancestor " + source).because("did not match"));
ConditionOutcome outcome = ConditionOutcome
.noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match"));
sourceOutcomes.add(ANCESTOR_CONDITION, outcome);
}
});
@@ -168,8 +167,7 @@ public final class ConditionEvaluationReport {
*/
public static ConditionEvaluationReport find(BeanFactory beanFactory) {
if (beanFactory != null && beanFactory instanceof ConfigurableBeanFactory) {
return ConditionEvaluationReport
.get((ConfigurableListableBeanFactory) beanFactory);
return ConditionEvaluationReport.get((ConfigurableListableBeanFactory) beanFactory);
}
return null;
}
@@ -179,8 +177,7 @@ public final class ConditionEvaluationReport {
* @param beanFactory the bean factory
* @return an existing or new {@link ConditionEvaluationReport}
*/
public static ConditionEvaluationReport get(
ConfigurableListableBeanFactory beanFactory) {
public static ConditionEvaluationReport get(ConfigurableListableBeanFactory beanFactory) {
synchronized (beanFactory) {
ConditionEvaluationReport report;
if (beanFactory.containsSingleton(BEAN_NAME)) {
@@ -195,12 +192,9 @@ public final class ConditionEvaluationReport {
}
}
private static void locateParent(BeanFactory beanFactory,
ConditionEvaluationReport report) {
if (beanFactory != null && report.parent == null
&& beanFactory.containsBean(BEAN_NAME)) {
report.parent = beanFactory.getBean(BEAN_NAME,
ConditionEvaluationReport.class);
private static void locateParent(BeanFactory beanFactory, ConditionEvaluationReport report) {
if (beanFactory != null && report.parent == null && beanFactory.containsBean(BEAN_NAME)) {
report.parent = beanFactory.getBean(BEAN_NAME, ConditionEvaluationReport.class);
}
}
@@ -208,12 +202,9 @@ public final class ConditionEvaluationReport {
ConditionEvaluationReport delta = new ConditionEvaluationReport();
this.outcomes.forEach((source, sourceOutcomes) -> {
ConditionAndOutcomes previous = previousReport.outcomes.get(source);
if (previous == null
|| previous.isFullMatch() != sourceOutcomes.isFullMatch()) {
sourceOutcomes.forEach(
(conditionAndOutcome) -> delta.recordConditionEvaluation(source,
conditionAndOutcome.getCondition(),
conditionAndOutcome.getOutcome()));
if (previous == null || previous.isFullMatch() != sourceOutcomes.isFullMatch()) {
sourceOutcomes.forEach((conditionAndOutcome) -> delta.recordConditionEvaluation(source,
conditionAndOutcome.getCondition(), conditionAndOutcome.getOutcome()));
}
});
List<String> newExclusions = new ArrayList<>(this.exclusions);
@@ -287,8 +278,7 @@ public final class ConditionEvaluationReport {
return false;
}
ConditionAndOutcome other = (ConditionAndOutcome) obj;
return (ObjectUtils.nullSafeEquals(this.condition.getClass(),
other.condition.getClass())
return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass())
&& ObjectUtils.nullSafeEquals(this.outcome, other.outcome));
}

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");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ class ConditionEvaluationReportAutoConfigurationImportListener
@Override
public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {
if (this.beanFactory != null) {
ConditionEvaluationReport report = ConditionEvaluationReport
.get(this.beanFactory);
ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory);
report.recordEvaluationCandidates(event.getCandidateConfigurations());
report.recordExclusions(event.getExclusions());
}

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");
* you may not use this file except in compliance with the License.
@@ -106,8 +106,7 @@ public final class ConditionMessage {
* @see #andCondition(String, Object...)
* @see #forCondition(Class, Object...)
*/
public Builder andCondition(Class<? extends Annotation> condition,
Object... details) {
public Builder andCondition(Class<? extends Annotation> condition, Object... details) {
Assert.notNull(condition, "Condition must not be null");
return andCondition("@" + ClassUtils.getShortName(condition), details);
}
@@ -177,8 +176,7 @@ public final class ConditionMessage {
* @see #forCondition(String, Object...)
* @see #andCondition(String, Object...)
*/
public static Builder forCondition(Class<? extends Annotation> condition,
Object... details) {
public static Builder forCondition(Class<? extends Annotation> condition, Object... details) {
return new ConditionMessage().andCondition(condition, details);
}
@@ -301,8 +299,8 @@ public final class ConditionMessage {
if (StringUtils.isEmpty(reason)) {
return new ConditionMessage(ConditionMessage.this, this.condition);
}
return new ConditionMessage(ConditionMessage.this, this.condition
+ (StringUtils.isEmpty(this.condition) ? "" : " ") + reason);
return new ConditionMessage(ConditionMessage.this,
this.condition + (StringUtils.isEmpty(this.condition) ? "" : " ") + reason);
}
}
@@ -320,8 +318,7 @@ public final class ConditionMessage {
private final String plural;
private ItemsBuilder(Builder condition, String reason, String singular,
String plural) {
private ItemsBuilder(Builder condition, String reason, String singular, String plural) {
this.condition = condition;
this.reason = reason;
this.singular = singular;
@@ -384,16 +381,14 @@ public final class ConditionMessage {
Assert.notNull(style, "Style must not be null");
StringBuilder message = new StringBuilder(this.reason);
items = style.applyTo(items);
if ((this.condition == null || items.size() <= 1)
&& StringUtils.hasLength(this.singular)) {
if ((this.condition == null || items.size() <= 1) && StringUtils.hasLength(this.singular)) {
message.append(" " + this.singular);
}
else if (StringUtils.hasLength(this.plural)) {
message.append(" " + this.plural);
}
if (items != null && !items.isEmpty()) {
message.append(
" " + StringUtils.collectionToDelimitedString(items, ", "));
message.append(" " + StringUtils.collectionToDelimitedString(items, ", "));
}
return this.condition.because(message.toString());
}

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");
* you may not use this file except in compliance with the License.
@@ -132,16 +132,14 @@ public class ConditionOutcome {
}
if (getClass() == obj.getClass()) {
ConditionOutcome other = (ConditionOutcome) obj;
return (this.match == other.match
&& ObjectUtils.nullSafeEquals(this.message, other.message));
return (this.match == other.match && ObjectUtils.nullSafeEquals(this.message, other.message));
}
return super.equals(obj);
}
@Override
public int hashCode() {
return Boolean.hashCode(this.match) * 31
+ ObjectUtils.nullSafeHashCode(this.message);
return Boolean.hashCode(this.match) * 31 + ObjectUtils.nullSafeHashCode(this.message);
}
@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");
* you may not use this file except in compliance with the License.
@@ -44,20 +44,16 @@ abstract class FilteringSpringBootCondition extends SpringBootCondition
private ClassLoader beanClassLoader;
@Override
public boolean[] match(String[] autoConfigurationClasses,
AutoConfigurationMetadata autoConfigurationMetadata) {
ConditionEvaluationReport report = ConditionEvaluationReport
.find(this.beanFactory);
ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses,
autoConfigurationMetadata);
public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
ConditionEvaluationReport report = ConditionEvaluationReport.find(this.beanFactory);
ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, autoConfigurationMetadata);
boolean[] match = new boolean[outcomes.length];
for (int i = 0; i < outcomes.length; i++) {
match[i] = (outcomes[i] == null || outcomes[i].isMatch());
if (!match[i] && outcomes[i] != null) {
logOutcome(autoConfigurationClasses[i], outcomes[i]);
if (report != null) {
report.recordConditionEvaluation(autoConfigurationClasses[i], this,
outcomes[i]);
report.recordConditionEvaluation(autoConfigurationClasses[i], this, outcomes[i]);
}
}
}
@@ -85,8 +81,8 @@ abstract class FilteringSpringBootCondition extends SpringBootCondition
this.beanClassLoader = classLoader;
}
protected List<String> filter(Collection<String> classNames,
ClassNameFilter classNameFilter, ClassLoader classLoader) {
protected List<String> filter(Collection<String> classNames, ClassNameFilter classNameFilter,
ClassLoader classLoader) {
if (CollectionUtils.isEmpty(classNames)) {
return Collections.emptyList();
}
@@ -134,8 +130,7 @@ abstract class FilteringSpringBootCondition extends SpringBootCondition
}
}
private static Class<?> forName(String className, ClassLoader classLoader)
throws ClassNotFoundException {
private static Class<?> forName(String className, ClassLoader classLoader) throws ClassNotFoundException {
if (classLoader != null) {
return classLoader.loadClass(className);
}

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");
* you may not use this file except in compliance with the License.
@@ -62,9 +62,8 @@ public abstract class NoneNestedConditions extends AbstractNestedCondition {
protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) {
boolean match = memberOutcomes.getMatches().isEmpty();
List<ConditionMessage> messages = new ArrayList<>();
messages.add(ConditionMessage.forCondition("NoneNestedConditions")
.because(memberOutcomes.getMatches().size() + " matched "
+ memberOutcomes.getNonMatches().size() + " did not"));
messages.add(ConditionMessage.forCondition("NoneNestedConditions").because(
memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not"));
for (ConditionOutcome outcome : memberOutcomes.getAll()) {
messages.add(outcome.getConditionMessage());
}

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");
* you may not use this file except in compliance with the License.
@@ -67,8 +67,7 @@ import org.springframework.util.StringUtils;
* @see ConditionalOnSingleCandidate
*/
@Order(Ordered.LOWEST_PRECEDENCE)
class OnBeanCondition extends FilteringSpringBootCondition
implements ConfigurationCondition {
class OnBeanCondition extends FilteringSpringBootCondition implements ConfigurationCondition {
/**
* Bean definition attribute name for factory beans to signal their product type (if
@@ -88,48 +87,40 @@ class OnBeanCondition extends FilteringSpringBootCondition
for (int i = 0; i < outcomes.length; i++) {
String autoConfigurationClass = autoConfigurationClasses[i];
if (autoConfigurationClass != null) {
Set<String> onBeanTypes = autoConfigurationMetadata
.getSet(autoConfigurationClass, "ConditionalOnBean");
Set<String> onBeanTypes = autoConfigurationMetadata.getSet(autoConfigurationClass, "ConditionalOnBean");
outcomes[i] = getOutcome(onBeanTypes, ConditionalOnBean.class);
if (outcomes[i] == null) {
Set<String> onSingleCandidateTypes = autoConfigurationMetadata.getSet(
autoConfigurationClass, "ConditionalOnSingleCandidate");
outcomes[i] = getOutcome(onSingleCandidateTypes,
ConditionalOnSingleCandidate.class);
Set<String> onSingleCandidateTypes = autoConfigurationMetadata.getSet(autoConfigurationClass,
"ConditionalOnSingleCandidate");
outcomes[i] = getOutcome(onSingleCandidateTypes, ConditionalOnSingleCandidate.class);
}
}
}
return outcomes;
}
private ConditionOutcome getOutcome(Set<String> requiredBeanTypes,
Class<? extends Annotation> annotation) {
List<String> missing = filter(requiredBeanTypes, ClassNameFilter.MISSING,
getBeanClassLoader());
private ConditionOutcome getOutcome(Set<String> requiredBeanTypes, Class<? extends Annotation> annotation) {
List<String> missing = filter(requiredBeanTypes, ClassNameFilter.MISSING, getBeanClassLoader());
if (!missing.isEmpty()) {
ConditionMessage message = ConditionMessage.forCondition(annotation)
.didNotFind("required type", "required types")
.items(Style.QUOTE, missing);
.didNotFind("required type", "required types").items(Style.QUOTE, missing);
return ConditionOutcome.noMatch(message);
}
return null;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage matchMessage = ConditionMessage.empty();
if (metadata.isAnnotated(ConditionalOnBean.class.getName())) {
BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
ConditionalOnBean.class);
BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnBean.class);
MatchResult matchResult = getMatchingBeans(context, spec);
if (!matchResult.isAllMatched()) {
String reason = createOnBeanNoMatchReason(matchResult);
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnBean.class, spec).because(reason));
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnBean.class, spec).because(reason));
}
matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec)
.found("bean", "beans")
matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec).found("bean", "beans")
.items(Style.QUOTE, matchResult.getNamesOfAllMatches());
}
if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
@@ -137,57 +128,47 @@ class OnBeanCondition extends FilteringSpringBootCondition
ConditionalOnSingleCandidate.class);
MatchResult matchResult = getMatchingBeans(context, spec);
if (!matchResult.isAllMatched()) {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnSingleCandidate.class, spec)
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec)
.didNotFind("any beans").atAll());
}
else if (!hasSingleAutowireCandidate(context.getBeanFactory(),
matchResult.getNamesOfAllMatches(),
else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matchResult.getNamesOfAllMatches(),
spec.getStrategy() == SearchStrategy.ALL)) {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnSingleCandidate.class, spec)
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec)
.didNotFind("a primary bean from beans")
.items(Style.QUOTE, matchResult.getNamesOfAllMatches()));
}
matchMessage = matchMessage
.andCondition(ConditionalOnSingleCandidate.class, spec)
.found("a primary bean from beans")
.items(Style.QUOTE, matchResult.getNamesOfAllMatches());
matchMessage = matchMessage.andCondition(ConditionalOnSingleCandidate.class, spec)
.found("a primary bean from beans").items(Style.QUOTE, matchResult.getNamesOfAllMatches());
}
if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
ConditionalOnMissingBean.class);
BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnMissingBean.class);
MatchResult matchResult = getMatchingBeans(context, spec);
if (matchResult.isAnyMatched()) {
String reason = createOnMissingBeanNoMatchReason(matchResult);
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnMissingBean.class, spec)
.because(reason));
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnMissingBean.class, spec).because(reason));
}
matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec)
.didNotFind("any beans").atAll();
matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec).didNotFind("any beans")
.atAll();
}
return ConditionOutcome.match(matchMessage);
}
protected final MatchResult getMatchingBeans(ConditionContext context,
BeanSearchSpec beans) {
protected final MatchResult getMatchingBeans(ConditionContext context, BeanSearchSpec beans) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
if (beans.getStrategy() == SearchStrategy.ANCESTORS) {
BeanFactory parent = beanFactory.getParentBeanFactory();
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
"Unable to use SearchStrategy.PARENTS");
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent, "Unable to use SearchStrategy.PARENTS");
beanFactory = (ConfigurableListableBeanFactory) parent;
}
MatchResult matchResult = new MatchResult();
boolean considerHierarchy = beans.getStrategy() != SearchStrategy.CURRENT;
TypeExtractor typeExtractor = beans.getTypeExtractor(context.getClassLoader());
List<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(
beans.getIgnoredTypes(), typeExtractor, beanFactory, context,
considerHierarchy);
List<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(beans.getIgnoredTypes(), typeExtractor,
beanFactory, context, considerHierarchy);
for (String type : beans.getTypes()) {
Collection<String> typeMatches = getBeanNamesForType(beanFactory, type,
typeExtractor, context.getClassLoader(), considerHierarchy);
Collection<String> typeMatches = getBeanNamesForType(beanFactory, type, typeExtractor,
context.getClassLoader(), considerHierarchy);
typeMatches.removeAll(beansIgnoredByType);
if (typeMatches.isEmpty()) {
matchResult.recordUnmatchedType(type);
@@ -197,9 +178,8 @@ class OnBeanCondition extends FilteringSpringBootCondition
}
}
for (String annotation : beans.getAnnotations()) {
List<String> annotationMatches = Arrays
.asList(getBeanNamesForAnnotation(beanFactory, annotation,
context.getClassLoader(), considerHierarchy));
List<String> annotationMatches = Arrays.asList(
getBeanNamesForAnnotation(beanFactory, annotation, context.getClassLoader(), considerHierarchy));
annotationMatches.removeAll(beansIgnoredByType);
if (annotationMatches.isEmpty()) {
matchResult.recordUnmatchedAnnotation(annotation);
@@ -209,8 +189,7 @@ class OnBeanCondition extends FilteringSpringBootCondition
}
}
for (String beanName : beans.getNames()) {
if (!beansIgnoredByType.contains(beanName)
&& containsBean(beanFactory, beanName, considerHierarchy)) {
if (!beansIgnoredByType.contains(beanName) && containsBean(beanFactory, beanName, considerHierarchy)) {
matchResult.recordMatchedName(beanName);
}
else {
@@ -220,16 +199,14 @@ class OnBeanCondition extends FilteringSpringBootCondition
return matchResult;
}
private String[] getBeanNamesForAnnotation(
ConfigurableListableBeanFactory beanFactory, String type,
private String[] getBeanNamesForAnnotation(ConfigurableListableBeanFactory beanFactory, String type,
ClassLoader classLoader, boolean considerHierarchy) throws LinkageError {
Set<String> names = new HashSet<>();
try {
@SuppressWarnings("unchecked")
Class<? extends Annotation> annotationType = (Class<? extends Annotation>) ClassUtils
.forName(type, classLoader);
collectBeanNamesForAnnotation(names, beanFactory, annotationType,
considerHierarchy);
Class<? extends Annotation> annotationType = (Class<? extends Annotation>) ClassUtils.forName(type,
classLoader);
collectBeanNamesForAnnotation(names, beanFactory, annotationType, considerHierarchy);
}
catch (ClassNotFoundException ex) {
// Continue
@@ -237,86 +214,75 @@ class OnBeanCondition extends FilteringSpringBootCondition
return StringUtils.toStringArray(names);
}
private void collectBeanNamesForAnnotation(Set<String> names,
ListableBeanFactory beanFactory, Class<? extends Annotation> annotationType,
boolean considerHierarchy) {
private void collectBeanNamesForAnnotation(Set<String> names, ListableBeanFactory beanFactory,
Class<? extends Annotation> annotationType, boolean considerHierarchy) {
BeanTypeRegistry registry = BeanTypeRegistry.get(beanFactory);
names.addAll(registry.getNamesForAnnotation(annotationType));
if (considerHierarchy) {
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory)
.getParentBeanFactory();
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory();
if (parent instanceof ListableBeanFactory) {
collectBeanNamesForAnnotation(names, (ListableBeanFactory) parent,
annotationType, considerHierarchy);
collectBeanNamesForAnnotation(names, (ListableBeanFactory) parent, annotationType, considerHierarchy);
}
}
}
private List<String> getNamesOfBeansIgnoredByType(List<String> ignoredTypes,
TypeExtractor typeExtractor, ListableBeanFactory beanFactory,
ConditionContext context, boolean considerHierarchy) {
private List<String> getNamesOfBeansIgnoredByType(List<String> ignoredTypes, TypeExtractor typeExtractor,
ListableBeanFactory beanFactory, ConditionContext context, boolean considerHierarchy) {
List<String> beanNames = new ArrayList<>();
for (String ignoredType : ignoredTypes) {
beanNames.addAll(getBeanNamesForType(beanFactory, ignoredType, typeExtractor,
context.getClassLoader(), considerHierarchy));
beanNames.addAll(getBeanNamesForType(beanFactory, ignoredType, typeExtractor, context.getClassLoader(),
considerHierarchy));
}
return beanNames;
}
private boolean containsBean(ConfigurableListableBeanFactory beanFactory,
String beanName, boolean considerHierarchy) {
private boolean containsBean(ConfigurableListableBeanFactory beanFactory, String beanName,
boolean considerHierarchy) {
if (considerHierarchy) {
return beanFactory.containsBean(beanName);
}
return beanFactory.containsLocalBean(beanName);
}
private Collection<String> getBeanNamesForType(ListableBeanFactory beanFactory,
String type, TypeExtractor typeExtractor, ClassLoader classLoader,
boolean considerHierarchy) throws LinkageError {
private Collection<String> getBeanNamesForType(ListableBeanFactory beanFactory, String type,
TypeExtractor typeExtractor, ClassLoader classLoader, boolean considerHierarchy) throws LinkageError {
try {
return getBeanNamesForType(beanFactory, considerHierarchy,
ClassUtils.forName(type, classLoader), typeExtractor);
return getBeanNamesForType(beanFactory, considerHierarchy, ClassUtils.forName(type, classLoader),
typeExtractor);
}
catch (ClassNotFoundException | NoClassDefFoundError ex) {
return Collections.emptySet();
}
}
private Collection<String> getBeanNamesForType(ListableBeanFactory beanFactory,
boolean considerHierarchy, Class<?> type, TypeExtractor typeExtractor) {
private Collection<String> getBeanNamesForType(ListableBeanFactory beanFactory, boolean considerHierarchy,
Class<?> type, TypeExtractor typeExtractor) {
Set<String> result = new LinkedHashSet<>();
collectBeanNamesForType(result, beanFactory, type, typeExtractor,
considerHierarchy);
collectBeanNamesForType(result, beanFactory, type, typeExtractor, considerHierarchy);
return result;
}
private void collectBeanNamesForType(Set<String> result,
ListableBeanFactory beanFactory, Class<?> type, TypeExtractor typeExtractor,
boolean considerHierarchy) {
private void collectBeanNamesForType(Set<String> result, ListableBeanFactory beanFactory, Class<?> type,
TypeExtractor typeExtractor, boolean considerHierarchy) {
BeanTypeRegistry registry = BeanTypeRegistry.get(beanFactory);
result.addAll(registry.getNamesForType(type, typeExtractor));
if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory) {
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory)
.getParentBeanFactory();
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory();
if (parent instanceof ListableBeanFactory) {
collectBeanNamesForType(result, (ListableBeanFactory) parent, type,
typeExtractor, considerHierarchy);
collectBeanNamesForType(result, (ListableBeanFactory) parent, type, typeExtractor, considerHierarchy);
}
}
}
private String createOnBeanNoMatchReason(MatchResult matchResult) {
StringBuilder reason = new StringBuilder();
appendMessageForNoMatches(reason, matchResult.getUnmatchedAnnotations(),
"annotated with");
appendMessageForNoMatches(reason, matchResult.getUnmatchedAnnotations(), "annotated with");
appendMessageForNoMatches(reason, matchResult.getUnmatchedTypes(), "of type");
appendMessageForNoMatches(reason, matchResult.getUnmatchedNames(), "named");
return reason.toString();
}
private void appendMessageForNoMatches(StringBuilder reason,
Collection<String> unmatched, String description) {
private void appendMessageForNoMatches(StringBuilder reason, Collection<String> unmatched, String description) {
if (!unmatched.isEmpty()) {
if (reason.length() > 0) {
reason.append(" and ");
@@ -330,22 +296,20 @@ class OnBeanCondition extends FilteringSpringBootCondition
private String createOnMissingBeanNoMatchReason(MatchResult matchResult) {
StringBuilder reason = new StringBuilder();
appendMessageForMatches(reason, matchResult.getMatchedAnnotations(),
"annotated with");
appendMessageForMatches(reason, matchResult.getMatchedAnnotations(), "annotated with");
appendMessageForMatches(reason, matchResult.getMatchedTypes(), "of type");
if (!matchResult.getMatchedNames().isEmpty()) {
if (reason.length() > 0) {
reason.append(" and ");
}
reason.append("found beans named ");
reason.append(StringUtils
.collectionToDelimitedString(matchResult.getMatchedNames(), ", "));
reason.append(StringUtils.collectionToDelimitedString(matchResult.getMatchedNames(), ", "));
}
return reason.toString();
}
private void appendMessageForMatches(StringBuilder reason,
Map<String, Collection<String>> matches, String description) {
private void appendMessageForMatches(StringBuilder reason, Map<String, Collection<String>> matches,
String description) {
if (!matches.isEmpty()) {
matches.forEach((key, value) -> {
if (reason.length() > 0) {
@@ -361,20 +325,16 @@ class OnBeanCondition extends FilteringSpringBootCondition
}
}
private boolean hasSingleAutowireCandidate(
ConfigurableListableBeanFactory beanFactory, Set<String> beanNames,
private boolean hasSingleAutowireCandidate(ConfigurableListableBeanFactory beanFactory, Set<String> beanNames,
boolean considerHierarchy) {
return (beanNames.size() == 1
|| getPrimaryBeans(beanFactory, beanNames, considerHierarchy)
.size() == 1);
return (beanNames.size() == 1 || getPrimaryBeans(beanFactory, beanNames, considerHierarchy).size() == 1);
}
private List<String> getPrimaryBeans(ConfigurableListableBeanFactory beanFactory,
Set<String> beanNames, boolean considerHierarchy) {
private List<String> getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, Set<String> beanNames,
boolean considerHierarchy) {
List<String> primaryBeans = new ArrayList<>();
for (String beanName : beanNames) {
BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName,
considerHierarchy);
BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, considerHierarchy);
if (beanDefinition != null && beanDefinition.isPrimary()) {
primaryBeans.add(beanName);
}
@@ -382,15 +342,14 @@ class OnBeanCondition extends FilteringSpringBootCondition
return primaryBeans;
}
private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory,
String beanName, boolean considerHierarchy) {
private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory, String beanName,
boolean considerHierarchy) {
if (beanFactory.containsBeanDefinition(beanName)) {
return beanFactory.getBeanDefinition(beanName);
}
if (considerHierarchy && beanFactory
.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory
.getParentBeanFactory()), beanName, considerHierarchy);
if (considerHierarchy && beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory.getParentBeanFactory()), beanName,
considerHierarchy);
}
return null;
}
@@ -411,16 +370,15 @@ class OnBeanCondition extends FilteringSpringBootCondition
private final SearchStrategy strategy;
public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata,
Class<?> annotationType) {
public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class<?> annotationType) {
this(context, metadata, annotationType, null);
}
public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata,
Class<?> annotationType, Class<?> genericContainer) {
public BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class<?> annotationType,
Class<?> genericContainer) {
this.annotationType = annotationType;
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(annotationType.getName(), true);
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(annotationType.getName(),
true);
collect(attributes, "name", this.names);
collect(attributes, "value", this.types);
collect(attributes, "type", this.types);
@@ -443,13 +401,11 @@ class OnBeanCondition extends FilteringSpringBootCondition
protected void validate(BeanTypeDeductionException ex) {
if (!hasAtLeastOne(this.types, this.names, this.annotations)) {
String message = getAnnotationName()
+ " did not specify a bean using type, name or annotation";
String message = getAnnotationName() + " did not specify a bean using type, name or annotation";
if (ex == null) {
throw new IllegalStateException(message);
}
throw new IllegalStateException(message + " and the attempt to deduce"
+ " the bean's type failed", ex);
throw new IllegalStateException(message + " and the attempt to deduce" + " the bean's type failed", ex);
}
}
@@ -461,8 +417,7 @@ class OnBeanCondition extends FilteringSpringBootCondition
return "@" + ClassUtils.getShortName(this.annotationType);
}
protected void collect(MultiValueMap<String, Object> attributes, String key,
List<String> destination) {
protected void collect(MultiValueMap<String, Object> attributes, String key, List<String> destination) {
List<?> values = attributes.get(key);
if (values != null) {
for (Object value : values) {
@@ -476,24 +431,21 @@ class OnBeanCondition extends FilteringSpringBootCondition
}
}
private void addDeducedBeanType(ConditionContext context,
AnnotatedTypeMetadata metadata, final List<String> beanTypes) {
if (metadata instanceof MethodMetadata
&& metadata.isAnnotated(Bean.class.getName())) {
addDeducedBeanTypeForBeanMethod(context, (MethodMetadata) metadata,
beanTypes);
private void addDeducedBeanType(ConditionContext context, AnnotatedTypeMetadata metadata,
final List<String> beanTypes) {
if (metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName())) {
addDeducedBeanTypeForBeanMethod(context, (MethodMetadata) metadata, beanTypes);
}
}
private void addDeducedBeanTypeForBeanMethod(ConditionContext context,
MethodMetadata metadata, final List<String> beanTypes) {
private void addDeducedBeanTypeForBeanMethod(ConditionContext context, MethodMetadata metadata,
final List<String> beanTypes) {
try {
Class<?> returnType = getReturnType(context, metadata);
beanTypes.add(returnType.getName());
}
catch (Throwable ex) {
throw new BeanTypeDeductionException(metadata.getDeclaringClassName(),
metadata.getMethodName(), ex);
throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), metadata.getMethodName(), ex);
}
}
@@ -502,18 +454,16 @@ class OnBeanCondition extends FilteringSpringBootCondition
// We should be safe to load at this point since we are in the
// REGISTER_BEAN phase
ClassLoader classLoader = context.getClassLoader();
Class<?> returnType = ClassUtils.forName(metadata.getReturnTypeName(),
classLoader);
Class<?> returnType = ClassUtils.forName(metadata.getReturnTypeName(), classLoader);
if (isParameterizedContainer(returnType, classLoader)) {
returnType = getReturnTypeGeneric(metadata, classLoader);
}
return returnType;
}
private Class<?> getReturnTypeGeneric(MethodMetadata metadata,
ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
Class<?> declaringClass = ClassUtils.forName(metadata.getDeclaringClassName(),
classLoader);
private Class<?> getReturnTypeGeneric(MethodMetadata metadata, ClassLoader classLoader)
throws ClassNotFoundException, LinkageError {
Class<?> declaringClass = ClassUtils.forName(metadata.getDeclaringClassName(), classLoader);
Method beanMethod = findBeanMethod(declaringClass, metadata.getMethodName());
return ResolvableType.forMethodReturnType(beanMethod).resolveGeneric();
}
@@ -524,15 +474,13 @@ class OnBeanCondition extends FilteringSpringBootCondition
return method;
}
return Arrays.stream(ReflectionUtils.getAllDeclaredMethods(declaringClass))
.filter((candidate) -> candidate.getName().equals(methodName))
.filter(this::isBeanMethod).findFirst()
.orElseThrow(() -> new IllegalStateException(
"Unable to find bean method " + methodName));
.filter((candidate) -> candidate.getName().equals(methodName)).filter(this::isBeanMethod)
.findFirst()
.orElseThrow(() -> new IllegalStateException("Unable to find bean method " + methodName));
}
private boolean isBeanMethod(Method method) {
return method != null
&& AnnotatedElementUtils.hasAnnotation(method, Bean.class);
return method != null && AnnotatedElementUtils.hasAnnotation(method, Bean.class);
}
public TypeExtractor getTypeExtractor(ClassLoader classLoader) {
@@ -551,8 +499,7 @@ class OnBeanCondition extends FilteringSpringBootCondition
private boolean isParameterizedContainer(Class<?> type, ClassLoader classLoader) {
for (String candidate : this.parameterizedContainers) {
try {
if (ClassUtils.forName(candidate, classLoader)
.isAssignableFrom(type)) {
if (ClassUtils.forName(candidate, classLoader).isAssignableFrom(type)) {
return true;
}
}
@@ -607,22 +554,21 @@ class OnBeanCondition extends FilteringSpringBootCondition
private static class SingleCandidateBeanSearchSpec extends BeanSearchSpec {
SingleCandidateBeanSearchSpec(ConditionContext context,
AnnotatedTypeMetadata metadata, Class<?> annotationType) {
SingleCandidateBeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata,
Class<?> annotationType) {
super(context, metadata, annotationType);
}
@Override
protected void collect(MultiValueMap<String, Object> attributes, String key,
List<String> destination) {
protected void collect(MultiValueMap<String, Object> attributes, String key, List<String> destination) {
super.collect(attributes, key, destination);
destination.removeAll(Arrays.asList("", Object.class.getName()));
}
@Override
protected void validate(BeanTypeDeductionException ex) {
Assert.isTrue(getTypes().size() == 1, () -> getAnnotationName()
+ " annotations must specify only one type (got " + getTypes() + ")");
Assert.isTrue(getTypes().size() == 1,
() -> getAnnotationName() + " annotations must specify only one type (got " + getTypes() + ")");
}
}
@@ -652,8 +598,7 @@ class OnBeanCondition extends FilteringSpringBootCondition
this.unmatchedNames.add(name);
}
private void recordMatchedAnnotation(String annotation,
Collection<String> matchingNames) {
private void recordMatchedAnnotation(String annotation, Collection<String> matchingNames) {
this.matchedAnnotations.put(annotation, matchingNames);
this.namesOfAllMatches.addAll(matchingNames);
}
@@ -713,10 +658,8 @@ class OnBeanCondition extends FilteringSpringBootCondition
static final class BeanTypeDeductionException extends RuntimeException {
private BeanTypeDeductionException(String className, String beanMethodName,
Throwable cause) {
super("Failed to deduce bean type for " + className + "." + beanMethodName,
cause);
private BeanTypeDeductionException(String className, String beanMethodName, Throwable cause) {
super("Failed to deduce bean type for " + className + "." + beanMethodName, cause);
}
}

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");
* you may not use this file except in compliance with the License.
@@ -50,11 +50,10 @@ class OnClassCondition extends FilteringSpringBootCondition {
// additional thread seems to offer the best performance. More threads make
// things worse
int split = autoConfigurationClasses.length / 2;
OutcomesResolver firstHalfResolver = createOutcomesResolver(
autoConfigurationClasses, 0, split, autoConfigurationMetadata);
OutcomesResolver secondHalfResolver = new StandardOutcomesResolver(
autoConfigurationClasses, split, autoConfigurationClasses.length,
autoConfigurationMetadata, getBeanClassLoader());
OutcomesResolver firstHalfResolver = createOutcomesResolver(autoConfigurationClasses, 0, split,
autoConfigurationMetadata);
OutcomesResolver secondHalfResolver = new StandardOutcomesResolver(autoConfigurationClasses, split,
autoConfigurationClasses.length, autoConfigurationMetadata, getBeanClassLoader());
ConditionOutcome[] secondHalf = secondHalfResolver.resolveOutcomes();
ConditionOutcome[] firstHalf = firstHalfResolver.resolveOutcomes();
ConditionOutcome[] outcomes = new ConditionOutcome[autoConfigurationClasses.length];
@@ -63,11 +62,10 @@ class OnClassCondition extends FilteringSpringBootCondition {
return outcomes;
}
private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses,
int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) {
OutcomesResolver outcomesResolver = new StandardOutcomesResolver(
autoConfigurationClasses, start, end, autoConfigurationMetadata,
getBeanClassLoader());
private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, int start, int end,
AutoConfigurationMetadata autoConfigurationMetadata) {
OutcomesResolver outcomesResolver = new StandardOutcomesResolver(autoConfigurationClasses, start, end,
autoConfigurationMetadata, getBeanClassLoader());
try {
return new ThreadedOutcomesResolver(outcomesResolver);
}
@@ -77,47 +75,36 @@ class OnClassCondition extends FilteringSpringBootCondition {
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ClassLoader classLoader = context.getClassLoader();
ConditionMessage matchMessage = ConditionMessage.empty();
List<String> onClasses = getCandidates(metadata, ConditionalOnClass.class);
if (onClasses != null) {
List<String> missing = filter(onClasses, ClassNameFilter.MISSING,
classLoader);
List<String> missing = filter(onClasses, ClassNameFilter.MISSING, classLoader);
if (!missing.isEmpty()) {
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class)
.didNotFind("required class", "required classes")
.items(Style.QUOTE, missing));
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class)
.didNotFind("required class", "required classes").items(Style.QUOTE, missing));
}
matchMessage = matchMessage.andCondition(ConditionalOnClass.class)
.found("required class", "required classes").items(Style.QUOTE,
filter(onClasses, ClassNameFilter.PRESENT, classLoader));
.found("required class", "required classes")
.items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader));
}
List<String> onMissingClasses = getCandidates(metadata,
ConditionalOnMissingClass.class);
List<String> onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class);
if (onMissingClasses != null) {
List<String> present = filter(onMissingClasses, ClassNameFilter.PRESENT,
classLoader);
List<String> present = filter(onMissingClasses, ClassNameFilter.PRESENT, classLoader);
if (!present.isEmpty()) {
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(ConditionalOnMissingClass.class)
.found("unwanted class", "unwanted classes")
.items(Style.QUOTE, present));
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class)
.found("unwanted class", "unwanted classes").items(Style.QUOTE, present));
}
matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class)
.didNotFind("unwanted class", "unwanted classes")
.items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING,
classLoader));
.items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, classLoader));
}
return ConditionOutcome.match(matchMessage);
}
private List<String> getCandidates(AnnotatedTypeMetadata metadata,
Class<?> annotationType) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(annotationType.getName(), true);
private List<String> getCandidates(AnnotatedTypeMetadata metadata, Class<?> annotationType) {
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), true);
if (attributes == null) {
return null;
}
@@ -148,8 +135,7 @@ class OnClassCondition extends FilteringSpringBootCondition {
private volatile ConditionOutcome[] outcomes;
private ThreadedOutcomesResolver(OutcomesResolver outcomesResolver) {
this.thread = new Thread(
() -> this.outcomes = outcomesResolver.resolveOutcomes());
this.thread = new Thread(() -> this.outcomes = outcomesResolver.resolveOutcomes());
this.thread.start();
}
@@ -178,9 +164,8 @@ class OnClassCondition extends FilteringSpringBootCondition {
private final ClassLoader beanClassLoader;
private StandardOutcomesResolver(String[] autoConfigurationClasses, int start,
int end, AutoConfigurationMetadata autoConfigurationMetadata,
ClassLoader beanClassLoader) {
private StandardOutcomesResolver(String[] autoConfigurationClasses, int start, int end,
AutoConfigurationMetadata autoConfigurationMetadata, ClassLoader beanClassLoader) {
this.autoConfigurationClasses = autoConfigurationClasses;
this.start = start;
this.end = end;
@@ -190,18 +175,16 @@ class OnClassCondition extends FilteringSpringBootCondition {
@Override
public ConditionOutcome[] resolveOutcomes() {
return getOutcomes(this.autoConfigurationClasses, this.start, this.end,
this.autoConfigurationMetadata);
return getOutcomes(this.autoConfigurationClasses, this.start, this.end, this.autoConfigurationMetadata);
}
private ConditionOutcome[] getOutcomes(String[] autoConfigurationClasses,
int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) {
private ConditionOutcome[] getOutcomes(String[] autoConfigurationClasses, int start, int end,
AutoConfigurationMetadata autoConfigurationMetadata) {
ConditionOutcome[] outcomes = new ConditionOutcome[end - start];
for (int i = start; i < end; i++) {
String autoConfigurationClass = autoConfigurationClasses[i];
if (autoConfigurationClass != null) {
String candidates = autoConfigurationMetadata
.get(autoConfigurationClass, "ConditionalOnClass");
String candidates = autoConfigurationMetadata.get(autoConfigurationClass, "ConditionalOnClass");
if (candidates != null) {
outcomes[i - start] = getOutcome(candidates);
}
@@ -215,10 +198,8 @@ class OnClassCondition extends FilteringSpringBootCondition {
if (!candidates.contains(",")) {
return getOutcome(candidates, this.beanClassLoader);
}
for (String candidate : StringUtils
.commaDelimitedListToStringArray(candidates)) {
ConditionOutcome outcome = getOutcome(candidate,
this.beanClassLoader);
for (String candidate : StringUtils.commaDelimitedListToStringArray(candidates)) {
ConditionOutcome outcome = getOutcome(candidate, this.beanClassLoader);
if (outcome != null) {
return outcome;
}
@@ -232,8 +213,7 @@ class OnClassCondition extends FilteringSpringBootCondition {
private ConditionOutcome getOutcome(String className, ClassLoader classLoader) {
if (ClassNameFilter.MISSING.matches(className, classLoader)) {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnClass.class)
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class)
.didNotFind("required class").items(Style.QUOTE, className));
}
return 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");
* you may not use this file except in compliance with the License.
@@ -33,19 +33,15 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
class OnCloudPlatformCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata
.getAnnotationAttributes(ConditionalOnCloudPlatform.class.getName());
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnCloudPlatform.class.getName());
CloudPlatform cloudPlatform = (CloudPlatform) attributes.get("value");
return getMatchOutcome(context.getEnvironment(), cloudPlatform);
}
private ConditionOutcome getMatchOutcome(Environment environment,
CloudPlatform cloudPlatform) {
private ConditionOutcome getMatchOutcome(Environment environment, CloudPlatform cloudPlatform) {
String name = cloudPlatform.name();
ConditionMessage.Builder message = ConditionMessage
.forCondition(ConditionalOnCloudPlatform.class);
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnCloudPlatform.class);
if (cloudPlatform.isActive(environment)) {
return ConditionOutcome.match(message.foundExactly(name));
}

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");
* you may not use this file except in compliance with the License.
@@ -36,32 +36,27 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
class OnExpressionCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
String expression = (String) metadata
.getAnnotationAttributes(ConditionalOnExpression.class.getName())
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String expression = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())
.get("value");
expression = wrapIfNecessary(expression);
ConditionMessage.Builder messageBuilder = ConditionMessage
.forCondition(ConditionalOnExpression.class, "(" + expression + ")");
ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class,
"(" + expression + ")");
expression = context.getEnvironment().resolvePlaceholders(expression);
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
if (beanFactory != null) {
boolean result = evaluateExpression(beanFactory, expression);
return new ConditionOutcome(result, messageBuilder.resultedIn(result));
}
return ConditionOutcome
.noMatch(messageBuilder.because("no BeanFactory available."));
return ConditionOutcome.noMatch(messageBuilder.because("no BeanFactory available."));
}
private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory,
String expression) {
private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, String expression) {
BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
if (resolver == null) {
resolver = new StandardBeanExpressionResolver();
}
BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory,
null);
BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, null);
Object result = resolver.evaluate(expression, expressionContext);
return (result != null && (boolean) result);
}

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");
* you may not use this file except in compliance with the License.
@@ -40,23 +40,17 @@ class OnJavaCondition extends SpringBootCondition {
private static final JavaVersion JVM_VERSION = JavaVersion.getJavaVersion();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata
.getAnnotationAttributes(ConditionalOnJava.class.getName());
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnJava.class.getName());
Range range = (Range) attributes.get("range");
JavaVersion version = (JavaVersion) attributes.get("value");
return getMatchOutcome(range, JVM_VERSION, version);
}
protected ConditionOutcome getMatchOutcome(Range range, JavaVersion runningVersion,
JavaVersion version) {
protected ConditionOutcome getMatchOutcome(Range range, JavaVersion runningVersion, JavaVersion version) {
boolean match = isWithin(runningVersion, range, version);
String expected = String.format(
(range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)",
version);
ConditionMessage message = ConditionMessage
.forCondition(ConditionalOnJava.class, expected)
String expected = String.format((range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", version);
ConditionMessage message = ConditionMessage.forCondition(ConditionalOnJava.class, expected)
.foundExactly(runningVersion);
return new ConditionOutcome(match, message);
}
@@ -68,8 +62,7 @@ class OnJavaCondition extends SpringBootCondition {
* @param version the bounds of the range
* @return if this version is within the specified range
*/
private boolean isWithin(JavaVersion runningVersion, Range range,
JavaVersion version) {
private boolean isWithin(JavaVersion runningVersion, Range range, JavaVersion version) {
if (range == Range.EQUAL_OR_NEWER) {
return runningVersion.isEqualOrNewerThan(version);
}

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");
* you may not use this file except in compliance with the License.
@@ -39,42 +39,37 @@ import org.springframework.util.StringUtils;
class OnJndiCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName()));
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName()));
String[] locations = annotationAttributes.getStringArray("value");
try {
return getMatchOutcome(locations);
}
catch (NoClassDefFoundError ex) {
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class)
.because("JNDI class not found"));
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found"));
}
}
private ConditionOutcome getMatchOutcome(String[] locations) {
if (!isJndiAvailable()) {
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class)
.notAvailable("JNDI environment"));
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment"));
}
if (locations.length == 0) {
return ConditionOutcome.match(ConditionMessage
.forCondition(ConditionalOnJndi.class).available("JNDI environment"));
return ConditionOutcome
.match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment"));
}
JndiLocator locator = getJndiLocator(locations);
String location = locator.lookupFirstLocation();
String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")";
if (location != null) {
return ConditionOutcome
.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.foundExactly("\"" + location + "\""));
return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.foundExactly("\"" + location + "\""));
}
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.didNotFind("any matching JNDI location").atAll());
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.didNotFind("any matching JNDI location").atAll());
}
protected boolean isJndiAvailable() {

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");
* you may not use this file except in compliance with the License.
@@ -47,16 +47,13 @@ import org.springframework.util.StringUtils;
class OnPropertyCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
List<AnnotationAttributes> allAnnotationAttributes = annotationAttributesFromMultiValueMap(
metadata.getAllAnnotationAttributes(
ConditionalOnProperty.class.getName()));
metadata.getAllAnnotationAttributes(ConditionalOnProperty.class.getName()));
List<ConditionMessage> noMatch = new ArrayList<>();
List<ConditionMessage> match = new ArrayList<>();
for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) {
ConditionOutcome outcome = determineOutcome(annotationAttributes,
context.getEnvironment());
ConditionOutcome outcome = determineOutcome(annotationAttributes, context.getEnvironment());
(outcome.isMatch() ? match : noMatch).add(outcome.getConditionMessage());
}
if (!noMatch.isEmpty()) {
@@ -88,27 +85,22 @@ class OnPropertyCondition extends SpringBootCondition {
return annotationAttributes;
}
private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes,
PropertyResolver resolver) {
private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, PropertyResolver resolver) {
Spec spec = new Spec(annotationAttributes);
List<String> missingProperties = new ArrayList<>();
List<String> nonMatchingProperties = new ArrayList<>();
spec.collectProperties(resolver, missingProperties, nonMatchingProperties);
if (!missingProperties.isEmpty()) {
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
.didNotFind("property", "properties")
.items(Style.QUOTE, missingProperties));
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
.didNotFind("property", "properties").items(Style.QUOTE, missingProperties));
}
if (!nonMatchingProperties.isEmpty()) {
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
.found("different value in property",
"different value in properties")
.items(Style.QUOTE, nonMatchingProperties));
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
.found("different value in property", "different value in properties")
.items(Style.QUOTE, nonMatchingProperties));
}
return ConditionOutcome.match(ConditionMessage
.forCondition(ConditionalOnProperty.class, spec).because("matched"));
return ConditionOutcome
.match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched"));
}
private static class Spec {
@@ -142,8 +134,7 @@ class OnPropertyCondition extends SpringBootCondition {
return (value.length > 0) ? value : name;
}
private void collectProperties(PropertyResolver resolver, List<String> missing,
List<String> nonMatching) {
private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) {
for (String name : this.names) {
String key = this.prefix + name;
if (resolver.containsProperty(key)) {

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");
* you may not use this file except in compliance with the License.
@@ -36,8 +36,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
*/
public class OnPropertyListCondition extends SpringBootCondition {
private static final Bindable<List<String>> STRING_LIST = Bindable
.listOf(String.class);
private static final Bindable<List<String>> STRING_LIST = Bindable.listOf(String.class);
private final String propertyName;
@@ -49,24 +48,19 @@ public class OnPropertyListCondition extends SpringBootCondition {
* @param messageBuilder a message builder supplier that should provide a fresh
* instance on each call
*/
protected OnPropertyListCondition(String propertyName,
Supplier<ConditionMessage.Builder> messageBuilder) {
protected OnPropertyListCondition(String propertyName, Supplier<ConditionMessage.Builder> messageBuilder) {
this.propertyName = propertyName;
this.messageBuilder = messageBuilder;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
BindResult<?> property = Binder.get(context.getEnvironment())
.bind(this.propertyName, STRING_LIST);
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
BindResult<?> property = Binder.get(context.getEnvironment()).bind(this.propertyName, STRING_LIST);
ConditionMessage.Builder messageBuilder = this.messageBuilder.get();
if (property.isBound()) {
return ConditionOutcome
.match(messageBuilder.found("property").items(this.propertyName));
return ConditionOutcome.match(messageBuilder.found("property").items(this.propertyName));
}
return ConditionOutcome
.noMatch(messageBuilder.didNotFind("property").items(this.propertyName));
return ConditionOutcome.noMatch(messageBuilder.didNotFind("property").items(this.propertyName));
}
}

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");
* you may not use this file except in compliance with the License.
@@ -42,17 +42,15 @@ class OnResourceCondition extends SpringBootCondition {
private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true);
ResourceLoader loader = (context.getResourceLoader() != null)
? context.getResourceLoader() : this.defaultResourceLoader;
ResourceLoader loader = (context.getResourceLoader() != null) ? context.getResourceLoader()
: this.defaultResourceLoader;
List<String> locations = new ArrayList<>();
collectValues(locations, attributes.get("resources"));
Assert.isTrue(!locations.isEmpty(),
"@ConditionalOnResource annotations must specify at "
+ "least one resource location");
"@ConditionalOnResource annotations must specify at " + "least one resource location");
List<String> missing = new ArrayList<>();
for (String location : locations) {
String resource = context.getEnvironment().resolvePlaceholders(location);
@@ -61,13 +59,11 @@ class OnResourceCondition extends SpringBootCondition {
}
}
if (!missing.isEmpty()) {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnResource.class)
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.class)
.didNotFind("resource", "resources").items(Style.QUOTE, missing));
}
return ConditionOutcome
.match(ConditionMessage.forCondition(ConditionalOnResource.class)
.found("location", "locations").items(locations));
return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.class)
.found("location", "locations").items(locations));
}
private void collectValues(List<String> names, List<Object> values) {

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");
* you may not use this file except in compliance with the License.
@@ -55,8 +55,8 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition {
for (int i = 0; i < outcomes.length; i++) {
String autoConfigurationClass = autoConfigurationClasses[i];
if (autoConfigurationClass != null) {
outcomes[i] = getOutcome(autoConfigurationMetadata
.get(autoConfigurationClass, "ConditionalOnWebApplication"));
outcomes[i] = getOutcome(
autoConfigurationMetadata.get(autoConfigurationClass, "ConditionalOnWebApplication"));
}
}
return outcomes;
@@ -66,37 +66,27 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition {
if (type == null) {
return null;
}
ConditionMessage.Builder message = ConditionMessage
.forCondition(ConditionalOnWebApplication.class);
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class);
if (ConditionalOnWebApplication.Type.SERVLET.name().equals(type)) {
if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS,
getBeanClassLoader())) {
return ConditionOutcome.noMatch(
message.didNotFind("servlet web application classes").atAll());
if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, getBeanClassLoader())) {
return ConditionOutcome.noMatch(message.didNotFind("servlet web application classes").atAll());
}
}
if (ConditionalOnWebApplication.Type.REACTIVE.name().equals(type)) {
if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS,
getBeanClassLoader())) {
return ConditionOutcome.noMatch(
message.didNotFind("reactive web application classes").atAll());
if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, getBeanClassLoader())) {
return ConditionOutcome.noMatch(message.didNotFind("reactive web application classes").atAll());
}
}
if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS,
getBeanClassLoader())
&& !ClassUtils.isPresent(REACTIVE_WEB_APPLICATION_CLASS,
getBeanClassLoader())) {
return ConditionOutcome.noMatch(message
.didNotFind("reactive or servlet web application classes").atAll());
if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, getBeanClassLoader())
&& !ClassUtils.isPresent(REACTIVE_WEB_APPLICATION_CLASS, getBeanClassLoader())) {
return ConditionOutcome.noMatch(message.didNotFind("reactive or servlet web application classes").atAll());
}
return null;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
boolean required = metadata
.isAnnotated(ConditionalOnWebApplication.class.getName());
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean required = metadata.isAnnotated(ConditionalOnWebApplication.class.getName());
ConditionOutcome outcome = isWebApplication(context, metadata, required);
if (required && !outcome.isMatch()) {
return ConditionOutcome.noMatch(outcome.getConditionMessage());
@@ -107,8 +97,8 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition {
return ConditionOutcome.match(outcome.getConditionMessage());
}
private ConditionOutcome isWebApplication(ConditionContext context,
AnnotatedTypeMetadata metadata, boolean required) {
private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata,
boolean required) {
switch (deduceType(metadata)) {
case SERVLET:
return isServletWebApplication(context);
@@ -119,31 +109,25 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition {
}
}
private ConditionOutcome isAnyWebApplication(ConditionContext context,
boolean required) {
ConditionMessage.Builder message = ConditionMessage.forCondition(
ConditionalOnWebApplication.class, required ? "(required)" : "");
private ConditionOutcome isAnyWebApplication(ConditionContext context, boolean required) {
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class,
required ? "(required)" : "");
ConditionOutcome servletOutcome = isServletWebApplication(context);
if (servletOutcome.isMatch() && required) {
return new ConditionOutcome(servletOutcome.isMatch(),
message.because(servletOutcome.getMessage()));
return new ConditionOutcome(servletOutcome.isMatch(), message.because(servletOutcome.getMessage()));
}
ConditionOutcome reactiveOutcome = isReactiveWebApplication(context);
if (reactiveOutcome.isMatch() && required) {
return new ConditionOutcome(reactiveOutcome.isMatch(),
message.because(reactiveOutcome.getMessage()));
return new ConditionOutcome(reactiveOutcome.isMatch(), message.because(reactiveOutcome.getMessage()));
}
return new ConditionOutcome(servletOutcome.isMatch() || reactiveOutcome.isMatch(),
message.because(servletOutcome.getMessage()).append("and")
.append(reactiveOutcome.getMessage()));
message.because(servletOutcome.getMessage()).append("and").append(reactiveOutcome.getMessage()));
}
private ConditionOutcome isServletWebApplication(ConditionContext context) {
ConditionMessage.Builder message = ConditionMessage.forCondition("");
if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS,
context.getClassLoader())) {
return ConditionOutcome.noMatch(
message.didNotFind("servlet web application classes").atAll());
if (!ClassNameFilter.isPresent(SERVLET_WEB_APPLICATION_CLASS, context.getClassLoader())) {
return ConditionOutcome.noMatch(message.didNotFind("servlet web application classes").atAll());
}
if (context.getBeanFactory() != null) {
String[] scopes = context.getBeanFactory().getRegisteredScopeNames();
@@ -152,8 +136,7 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition {
}
}
if (context.getEnvironment() instanceof ConfigurableWebEnvironment) {
return ConditionOutcome
.match(message.foundExactly("ConfigurableWebEnvironment"));
return ConditionOutcome.match(message.foundExactly("ConfigurableWebEnvironment"));
}
if (context.getResourceLoader() instanceof WebApplicationContext) {
return ConditionOutcome.match(message.foundExactly("WebApplicationContext"));
@@ -163,26 +146,20 @@ class OnWebApplicationCondition extends FilteringSpringBootCondition {
private ConditionOutcome isReactiveWebApplication(ConditionContext context) {
ConditionMessage.Builder message = ConditionMessage.forCondition("");
if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS,
context.getClassLoader())) {
return ConditionOutcome.noMatch(
message.didNotFind("reactive web application classes").atAll());
if (!ClassNameFilter.isPresent(REACTIVE_WEB_APPLICATION_CLASS, context.getClassLoader())) {
return ConditionOutcome.noMatch(message.didNotFind("reactive web application classes").atAll());
}
if (context.getEnvironment() instanceof ConfigurableReactiveWebEnvironment) {
return ConditionOutcome
.match(message.foundExactly("ConfigurableReactiveWebEnvironment"));
return ConditionOutcome.match(message.foundExactly("ConfigurableReactiveWebEnvironment"));
}
if (context.getResourceLoader() instanceof ReactiveWebApplicationContext) {
return ConditionOutcome
.match(message.foundExactly("ReactiveWebApplicationContext"));
return ConditionOutcome.match(message.foundExactly("ReactiveWebApplicationContext"));
}
return ConditionOutcome
.noMatch(message.because("not a reactive web application"));
return ConditionOutcome.noMatch(message.because("not a reactive web application"));
}
private Type deduceType(AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata
.getAnnotationAttributes(ConditionalOnWebApplication.class.getName());
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnWebApplication.class.getName());
if (attributes != null) {
return (Type) attributes.get("type");
}

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");
* you may not use this file except in compliance with the License.
@@ -51,19 +51,16 @@ public abstract class ResourceCondition extends SpringBootCondition {
* found if the configuration key is not specified
* @since 2.0.0
*/
protected ResourceCondition(String name, String property,
String... resourceLocations) {
protected ResourceCondition(String name, String property, String... resourceLocations) {
this.name = name;
this.property = property;
this.resourceLocations = resourceLocations;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getEnvironment().containsProperty(this.property)) {
return ConditionOutcome.match(
startConditionMessage().foundExactly("property " + this.property));
return ConditionOutcome.match(startConditionMessage().foundExactly("property " + this.property));
}
return getResourceOutcome(context, metadata);
}
@@ -74,8 +71,7 @@ public abstract class ResourceCondition extends SpringBootCondition {
* @param metadata the annotation metadata
* @return the condition outcome
*/
protected ConditionOutcome getResourceOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
List<String> found = new ArrayList<>();
for (String location : this.resourceLocations) {
Resource resource = context.getResourceLoader().getResource(location);
@@ -84,13 +80,11 @@ public abstract class ResourceCondition extends SpringBootCondition {
}
}
if (found.isEmpty()) {
ConditionMessage message = startConditionMessage()
.didNotFind("resource", "resources")
.items(Style.QUOTE, Arrays.asList(this.resourceLocations));
ConditionMessage message = startConditionMessage().didNotFind("resource", "resources").items(Style.QUOTE,
Arrays.asList(this.resourceLocations));
return ConditionOutcome.noMatch(message);
}
ConditionMessage message = startConditionMessage().found("resource", "resources")
.items(Style.QUOTE, found);
ConditionMessage message = startConditionMessage().found("resource", "resources").items(Style.QUOTE, found);
return ConditionOutcome.match(message);
}

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");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ public abstract class SpringBootCondition implements Condition {
private final Log logger = LogFactory.getLog(getClass());
@Override
public final boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String classOrMethodName = getClassOrMethodName(metadata);
try {
ConditionOutcome outcome = getMatchOutcome(context, metadata);
@@ -50,18 +49,14 @@ public abstract class SpringBootCondition implements Condition {
return outcome.isMatch();
}
catch (NoClassDefFoundError ex) {
throw new IllegalStateException(
"Could not evaluate condition on " + classOrMethodName + " due to "
+ ex.getMessage() + " not "
+ "found. Make sure your own configuration does not rely on "
+ "that class. This can also happen if you are "
+ "@ComponentScanning a springframework package (e.g. if you "
+ "put a @ComponentScan in the default package by mistake)",
ex);
throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to "
+ ex.getMessage() + " not " + "found. Make sure your own configuration does not rely on "
+ "that class. This can also happen if you are "
+ "@ComponentScanning a springframework package (e.g. if you "
+ "put a @ComponentScan in the default package by mistake)", ex);
}
catch (RuntimeException ex) {
throw new IllegalStateException(
"Error processing condition on " + getName(metadata), ex);
throw new IllegalStateException("Error processing condition on " + getName(metadata), ex);
}
}
@@ -71,8 +66,7 @@ public abstract class SpringBootCondition implements Condition {
}
if (metadata instanceof MethodMetadata) {
MethodMetadata methodMetadata = (MethodMetadata) metadata;
return methodMetadata.getDeclaringClassName() + "."
+ methodMetadata.getMethodName();
return methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName();
}
return metadata.toString();
}
@@ -83,8 +77,7 @@ public abstract class SpringBootCondition implements Condition {
return classMetadata.getClassName();
}
MethodMetadata methodMetadata = (MethodMetadata) metadata;
return methodMetadata.getDeclaringClassName() + "#"
+ methodMetadata.getMethodName();
return methodMetadata.getDeclaringClassName() + "#" + methodMetadata.getMethodName();
}
protected final void logOutcome(String classOrMethodName, ConditionOutcome outcome) {
@@ -93,8 +86,7 @@ public abstract class SpringBootCondition implements Condition {
}
}
private StringBuilder getLogMessage(String classOrMethodName,
ConditionOutcome outcome) {
private StringBuilder getLogMessage(String classOrMethodName, ConditionOutcome outcome) {
StringBuilder message = new StringBuilder();
message.append("Condition ");
message.append(ClassUtils.getShortName(getClass()));
@@ -108,11 +100,10 @@ public abstract class SpringBootCondition implements Condition {
return message;
}
private void recordEvaluation(ConditionContext context, String classOrMethodName,
ConditionOutcome outcome) {
private void recordEvaluation(ConditionContext context, String classOrMethodName, ConditionOutcome outcome) {
if (context.getBeanFactory() != null) {
ConditionEvaluationReport.get(context.getBeanFactory())
.recordConditionEvaluation(classOrMethodName, this, outcome);
ConditionEvaluationReport.get(context.getBeanFactory()).recordConditionEvaluation(classOrMethodName, this,
outcome);
}
}
@@ -122,8 +113,7 @@ public abstract class SpringBootCondition implements Condition {
* @param metadata the annotation metadata
* @return the condition outcome
*/
public abstract ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata);
public abstract ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata);
/**
* Return true if any of the specified conditions match.
@@ -132,8 +122,8 @@ public abstract class SpringBootCondition implements Condition {
* @param conditions conditions to test
* @return {@code true} if any condition matches.
*/
protected final boolean anyMatches(ConditionContext context,
AnnotatedTypeMetadata metadata, Condition... conditions) {
protected final boolean anyMatches(ConditionContext context, AnnotatedTypeMetadata metadata,
Condition... conditions) {
for (Condition condition : conditions) {
if (matches(context, metadata, condition)) {
return true;
@@ -149,11 +139,9 @@ public abstract class SpringBootCondition implements Condition {
* @param condition condition to test
* @return {@code true} if the condition matches.
*/
protected final boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata, Condition condition) {
protected final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata, Condition condition) {
if (condition instanceof SpringBootCondition) {
return ((SpringBootCondition) condition).getMatchOutcome(context, metadata)
.isMatch();
return ((SpringBootCondition) condition).getMatchOutcome(context, metadata).isMatch();
}
return condition.matches(context, metadata);
}

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");
* you may not use this file except in compliance with the License.
@@ -67,8 +67,8 @@ public class MessageSourceAutoConfiguration {
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(properties.getBasename())));
messageSource.setBasenames(StringUtils
.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
@@ -88,10 +88,8 @@ public class MessageSourceAutoConfiguration {
private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<>();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment()
.getProperty("spring.messages.basename", "messages");
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
ConditionOutcome outcome = cache.get(basename);
if (outcome == null) {
outcome = getMatchOutcomeForBasename(context, basename);
@@ -100,21 +98,16 @@ public class MessageSourceAutoConfiguration {
return outcome;
}
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context,
String basename) {
ConditionMessage.Builder message = ConditionMessage
.forCondition("ResourceBundle");
for (String name : StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(basename))) {
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle");
for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) {
return ConditionOutcome
.match(message.found("bundle").items(resource));
return ConditionOutcome.match(message.found("bundle").items(resource));
}
}
}
return ConditionOutcome.noMatch(
message.didNotFind("bundle with basename " + basename).atAll());
return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
}
private Resource[] getResources(ClassLoader classLoader, String name) {

View File

@@ -70,8 +70,7 @@ public class CouchbaseAutoConfiguration {
}
@ConditionalOnBean(
type = "org.springframework.data.couchbase.config.CouchbaseConfigurer")
@ConditionalOnBean(type = "org.springframework.data.couchbase.config.CouchbaseConfigurer")
static class CouchbaseConfigurerAvailable {
}

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");
* you may not use this file except in compliance with the License.
@@ -72,8 +72,9 @@ public class CouchbaseConfiguration {
@Primary
@DependsOn("couchbaseClient")
public ClusterInfo couchbaseClusterInfo() {
return couchbaseCluster().clusterManager(this.properties.getBucket().getName(),
this.properties.getBucket().getPassword()).info();
return couchbaseCluster()
.clusterManager(this.properties.getBucket().getName(), this.properties.getBucket().getPassword())
.info();
}
@Bean
@@ -88,17 +89,14 @@ public class CouchbaseConfiguration {
* @param properties the couchbase properties to use
* @return the {@link DefaultCouchbaseEnvironment} builder.
*/
protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder(
CouchbaseProperties properties) {
protected DefaultCouchbaseEnvironment.Builder initializeEnvironmentBuilder(CouchbaseProperties properties) {
CouchbaseProperties.Endpoints endpoints = properties.getEnv().getEndpoints();
CouchbaseProperties.Timeouts timeouts = properties.getEnv().getTimeouts();
DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment
.builder();
DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment.builder();
if (timeouts.getConnect() != null) {
builder = builder.connectTimeout(timeouts.getConnect().toMillis());
}
builder = builder.keyValueServiceConfig(
KeyValueServiceConfig.create(endpoints.getKeyValue()));
builder = builder.keyValueServiceConfig(KeyValueServiceConfig.create(endpoints.getKeyValue()));
if (timeouts.getKeyValue() != null) {
builder = builder.kvTimeout(timeouts.getKeyValue().toMillis());
}
@@ -108,8 +106,7 @@ public class CouchbaseConfiguration {
builder = builder.viewServiceConfig(getViewServiceConfig(endpoints));
}
if (timeouts.getSocketConnect() != null) {
builder = builder
.socketConnectTimeout((int) timeouts.getSocketConnect().toMillis());
builder = builder.socketConnectTimeout((int) timeouts.getSocketConnect().toMillis());
}
if (timeouts.getView() != null) {
builder = builder.viewTimeout(timeouts.getView().toMillis());

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");
* you may not use this file except in compliance with the License.
@@ -194,8 +194,7 @@ public class CouchbaseProperties {
private String keyStorePassword;
public Boolean getEnabled() {
return (this.enabled != null) ? this.enabled
: StringUtils.hasText(this.keyStore);
return (this.enabled != null) ? this.enabled : StringUtils.hasText(this.keyStore);
}
public void setEnabled(Boolean enabled) {

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");
* you may not use this file except in compliance with the License.
@@ -29,8 +29,7 @@ import org.springframework.boot.autoconfigure.condition.OnPropertyListCondition;
class OnBootstrapHostsCondition extends OnPropertyListCondition {
OnBootstrapHostsCondition() {
super("spring.couchbase.bootstrap-hosts",
() -> ConditionMessage.forCondition("Couchbase Bootstrap Hosts"));
super("spring.couchbase.bootstrap-hosts", () -> ConditionMessage.forCondition("Couchbase Bootstrap Hosts"));
}
}

View File

@@ -40,13 +40,12 @@ public class PersistenceExceptionTranslationAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.dao.exceptiontranslation", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.dao.exceptiontranslation", name = "enabled", matchIfMissing = true)
public static PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(
Environment environment) {
PersistenceExceptionTranslationPostProcessor postProcessor = new PersistenceExceptionTranslationPostProcessor();
boolean proxyTargetClass = environment.getProperty(
"spring.aop.proxy-target-class", Boolean.class, Boolean.TRUE);
boolean proxyTargetClass = environment.getProperty("spring.aop.proxy-target-class", Boolean.class,
Boolean.TRUE);
postProcessor.setProxyTargetClass(proxyTargetClass);
return postProcessor;
}

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");
* you may not use this file except in compliance with the License.
@@ -45,8 +45,7 @@ import org.springframework.data.util.Streamable;
* @author Oliver Gierke
*/
public abstract class AbstractRepositoryConfigurationSourceSupport
implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware,
EnvironmentAware {
implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
private ResourceLoader resourceLoader;
@@ -55,29 +54,24 @@ public abstract class AbstractRepositoryConfigurationSourceSupport
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
new RepositoryConfigurationDelegate(getConfigurationSource(registry),
this.resourceLoader, this.environment).registerRepositoriesIn(registry,
getRepositoryConfigurationExtension());
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
new RepositoryConfigurationDelegate(getConfigurationSource(registry), this.resourceLoader, this.environment)
.registerRepositoriesIn(registry, getRepositoryConfigurationExtension());
}
private AnnotationRepositoryConfigurationSource getConfigurationSource(
BeanDefinitionRegistry beanDefinitionRegistry) {
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(
getConfiguration(), true);
return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(),
this.resourceLoader, this.environment, beanDefinitionRegistry) {
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getConfiguration(), true);
return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader,
this.environment, beanDefinitionRegistry) {
@Override
public Streamable<String> getBasePackages() {
return AbstractRepositoryConfigurationSourceSupport.this
.getBasePackages();
return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages();
}
@Override
public BootstrapMode getBootstrapMode() {
return AbstractRepositoryConfigurationSourceSupport.this
.getBootstrapMode();
return AbstractRepositoryConfigurationSourceSupport.this.getBootstrapMode();
}
};

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");
* you may not use this file except in compliance with the License.
@@ -35,29 +35,24 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
class OnRepositoryTypeCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(
ConditionalOnRepositoryType.class.getName(), true);
RepositoryType configuredType = getTypeProperty(context.getEnvironment(),
(String) attributes.get("store"));
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnRepositoryType.class.getName(),
true);
RepositoryType configuredType = getTypeProperty(context.getEnvironment(), (String) attributes.get("store"));
RepositoryType requiredType = (RepositoryType) attributes.get("type");
ConditionMessage.Builder message = ConditionMessage
.forCondition(ConditionalOnRepositoryType.class);
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnRepositoryType.class);
if (configuredType == requiredType || configuredType == RepositoryType.AUTO) {
return ConditionOutcome.match(message.because("configured type of '"
+ configuredType.name() + "' matched required type"));
return ConditionOutcome
.match(message.because("configured type of '" + configuredType.name() + "' matched required type"));
}
return ConditionOutcome
.noMatch(message.because("configured type (" + configuredType.name()
+ ") did not match required type (" + requiredType.name() + ")"));
return ConditionOutcome.noMatch(message.because("configured type (" + configuredType.name()
+ ") did not match required type (" + requiredType.name() + ")"));
}
private RepositoryType getTypeProperty(Environment environment, String store) {
return RepositoryType.valueOf(environment
.getProperty(String.format("spring.data.%s.repositories.type", store),
"auto")
.toUpperCase(Locale.ENGLISH));
return RepositoryType
.valueOf(environment.getProperty(String.format("spring.data.%s.repositories.type", store), "auto")
.toUpperCase(Locale.ENGLISH));
}
}

View File

@@ -73,8 +73,8 @@ public class CassandraDataAutoConfiguration {
private final Environment environment;
public CassandraDataAutoConfiguration(BeanFactory beanFactory,
CassandraProperties properties, Cluster cluster, Environment environment) {
public CassandraDataAutoConfiguration(BeanFactory beanFactory, CassandraProperties properties, Cluster cluster,
Environment environment) {
this.beanFactory = beanFactory;
this.properties = properties;
this.cluster = cluster;
@@ -83,19 +83,18 @@ public class CassandraDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public CassandraMappingContext cassandraMapping(
CassandraCustomConversions conversions) throws ClassNotFoundException {
public CassandraMappingContext cassandraMapping(CassandraCustomConversions conversions)
throws ClassNotFoundException {
CassandraMappingContext context = new CassandraMappingContext();
List<String> packages = EntityScanPackages.get(this.beanFactory)
.getPackageNames();
List<String> packages = EntityScanPackages.get(this.beanFactory).getPackageNames();
if (packages.isEmpty() && AutoConfigurationPackages.has(this.beanFactory)) {
packages = AutoConfigurationPackages.get(this.beanFactory);
}
if (!packages.isEmpty()) {
context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages));
}
PropertyMapper.get().from(this.properties::getKeyspaceName).whenHasText()
.as(this::createSimpleUserTypeResolver).to(context::setUserTypeResolver);
PropertyMapper.get().from(this.properties::getKeyspaceName).whenHasText().as(this::createSimpleUserTypeResolver)
.to(context::setUserTypeResolver);
context.setCustomConversions(conversions);
return context;
}
@@ -115,22 +114,19 @@ public class CassandraDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean(Session.class)
public CassandraSessionFactoryBean cassandraSession(CassandraConverter converter)
throws Exception {
public CassandraSessionFactoryBean cassandraSession(CassandraConverter converter) throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(this.cluster);
session.setConverter(converter);
session.setKeyspaceName(this.properties.getKeyspaceName());
Binder binder = Binder.get(this.environment);
binder.bind("spring.data.cassandra.schema-action", SchemaAction.class)
.ifBound(session::setSchemaAction);
binder.bind("spring.data.cassandra.schema-action", SchemaAction.class).ifBound(session::setSchemaAction);
return session;
}
@Bean
@ConditionalOnMissingBean
public CassandraTemplate cassandraTemplate(Session session,
CassandraConverter converter) throws Exception {
public CassandraTemplate cassandraTemplate(Session session, CassandraConverter converter) throws Exception {
return new CassandraTemplate(session, 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");
* you may not use this file except in compliance with the License.
@@ -55,15 +55,14 @@ public class CassandraReactiveDataAutoConfiguration {
}
@Bean
public ReactiveSessionFactory reactiveCassandraSessionFactory(
ReactiveSession reactiveCassandraSession) {
public ReactiveSessionFactory reactiveCassandraSessionFactory(ReactiveSession reactiveCassandraSession) {
return new DefaultReactiveSessionFactory(reactiveCassandraSession);
}
@Bean
@ConditionalOnMissingBean
public ReactiveCassandraTemplate reactiveCassandraTemplate(
ReactiveSession reactiveCassandraSession, CassandraConverter converter) {
public ReactiveCassandraTemplate reactiveCassandraTemplate(ReactiveSession reactiveCassandraSession,
CassandraConverter converter) {
return new ReactiveCassandraTemplate(reactiveCassandraSession, converter);
}

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");
* you may not use this file except in compliance with the License.
@@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Eddú Meléndez
* @since 2.0.0
*/
class CassandraReactiveRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class CassandraReactiveRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

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");
* you may not use this file except in compliance with the License.
@@ -31,8 +31,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Eddú Meléndez
* @since 1.3.0
*/
class CassandraRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class CassandraRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

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");
* you may not use this file except in compliance with the License.
@@ -44,10 +44,8 @@ class CouchbaseConfigurerAdapterConfiguration {
@Bean
@ConditionalOnMissingBean
public CouchbaseConfigurer springBootCouchbaseConfigurer() throws Exception {
return new SpringBootCouchbaseConfigurer(
this.configuration.couchbaseEnvironment(),
this.configuration.couchbaseCluster(),
this.configuration.couchbaseClusterInfo(),
return new SpringBootCouchbaseConfigurer(this.configuration.couchbaseEnvironment(),
this.configuration.couchbaseCluster(), this.configuration.couchbaseClusterInfo(),
this.configuration.couchbaseClient());
}

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");
* you may not use this file except in compliance with the License.
@@ -42,11 +42,9 @@ import org.springframework.data.couchbase.repository.CouchbaseRepository;
*/
@Configuration
@ConditionalOnClass({ Bucket.class, CouchbaseRepository.class })
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class,
ValidationAutoConfiguration.class })
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, ValidationAutoConfiguration.class })
@EnableConfigurationProperties(CouchbaseDataProperties.class)
@Import({ CouchbaseConfigurerAdapterConfiguration.class,
SpringBootCouchbaseDataConfiguration.class })
@Import({ CouchbaseConfigurerAdapterConfiguration.class, SpringBootCouchbaseDataConfiguration.class })
public class CouchbaseDataAutoConfiguration {
@Configuration
@@ -55,8 +53,7 @@ public class CouchbaseDataAutoConfiguration {
@Bean
@ConditionalOnSingleCandidate(Validator.class)
public ValidatingCouchbaseEventListener validationEventListener(
Validator validator) {
public ValidatingCouchbaseEventListener validationEventListener(Validator validator) {
return new ValidatingCouchbaseEventListener(validator);
}

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");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
*
* @author Alex Derkach
*/
class CouchbaseReactiveRepositoriesRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class CouchbaseReactiveRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

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");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
*
* @author Eddú Meléndez
*/
class CouchbaseRepositoriesRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class CouchbaseRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

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");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,8 @@ public class SpringBootCouchbaseConfigurer implements CouchbaseConfigurer {
private final Bucket bucket;
public SpringBootCouchbaseConfigurer(CouchbaseEnvironment env, Cluster cluster,
ClusterInfo clusterInfo, Bucket bucket) {
public SpringBootCouchbaseConfigurer(CouchbaseEnvironment env, Cluster cluster, ClusterInfo clusterInfo,
Bucket bucket) {
this.env = env;
this.cluster = cluster;
this.clusterInfo = clusterInfo;

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");
* you may not use this file except in compliance with the License.
@@ -51,8 +51,7 @@ class SpringBootCouchbaseDataConfiguration extends AbstractCouchbaseDataConfigur
private final CouchbaseConfigurer couchbaseConfigurer;
SpringBootCouchbaseDataConfiguration(ApplicationContext applicationContext,
CouchbaseDataProperties properties,
SpringBootCouchbaseDataConfiguration(ApplicationContext applicationContext, CouchbaseDataProperties properties,
ObjectProvider<CouchbaseConfigurer> couchbaseConfigurer) {
this.applicationContext = applicationContext;
this.properties = properties;
@@ -71,8 +70,7 @@ class SpringBootCouchbaseDataConfiguration extends AbstractCouchbaseDataConfigur
@Override
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException {
return new EntityScanner(this.applicationContext).scan(Document.class,
Persistent.class);
return new EntityScanner(this.applicationContext).scan(Document.class, Persistent.class);
}
@Override

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");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ import org.springframework.data.couchbase.repository.config.ReactiveRepositoryOp
@Configuration
@ConditionalOnMissingBean(AbstractReactiveCouchbaseDataConfiguration.class)
@ConditionalOnBean(CouchbaseConfigurer.class)
class SpringBootCouchbaseReactiveDataConfiguration
extends AbstractReactiveCouchbaseDataConfiguration {
class SpringBootCouchbaseReactiveDataConfiguration extends AbstractReactiveCouchbaseDataConfiguration {
private final CouchbaseDataProperties properties;

View File

@@ -40,8 +40,7 @@ import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;
*/
@Configuration
@ConditionalOnClass({ Client.class, TransportClientFactoryBean.class })
@ConditionalOnProperty(prefix = "spring.data.elasticsearch", name = "cluster-nodes",
matchIfMissing = false)
@ConditionalOnProperty(prefix = "spring.data.elasticsearch", name = "cluster-nodes", matchIfMissing = false)
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchAutoConfiguration {

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");
* you may not use this file except in compliance with the License.
@@ -51,8 +51,7 @@ public class ElasticsearchDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(Client.class)
public ElasticsearchTemplate elasticsearchTemplate(Client client,
ElasticsearchConverter converter) {
public ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter) {
try {
return new ElasticsearchTemplate(client, converter);
}
@@ -63,8 +62,7 @@ public class ElasticsearchDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ElasticsearchConverter elasticsearchConverter(
SimpleElasticsearchMappingContext mappingContext) {
public ElasticsearchConverter elasticsearchConverter(SimpleElasticsearchMappingContext mappingContext) {
return new MappingElasticsearchConverter(mappingContext);
}

View File

@@ -39,8 +39,8 @@ import org.springframework.data.elasticsearch.repository.support.ElasticsearchRe
*/
@Configuration
@ConditionalOnClass({ Client.class, ElasticsearchRepository.class })
@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories",
name = "enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.elasticsearch.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnMissingBean(ElasticsearchRepositoryFactoryBean.class)
@Import(ElasticsearchRepositoriesRegistrar.class)
public class ElasticsearchRepositoriesAutoConfiguration {

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");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Mohsin Husen
* @since 1.1.0
*/
class ElasticsearchRepositoriesRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class ElasticsearchRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

View File

@@ -50,8 +50,8 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
@Configuration
@ConditionalOnBean(NamedParameterJdbcOperations.class)
@ConditionalOnClass({ NamedParameterJdbcOperations.class, JdbcConfiguration.class })
@ConditionalOnProperty(prefix = "spring.data.jdbc.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.jdbc.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@AutoConfigureAfter(JdbcTemplateAutoConfiguration.class)
public class JdbcRepositoriesAutoConfiguration {
@@ -74,14 +74,12 @@ public class JdbcRepositoriesAutoConfiguration {
}
@Override
public RelationalMappingContext jdbcMappingContext(
Optional<NamingStrategy> namingStrategy) {
public RelationalMappingContext jdbcMappingContext(Optional<NamingStrategy> namingStrategy) {
return super.jdbcMappingContext(namingStrategy);
}
@Override
public RelationalConverter relationalConverter(
RelationalMappingContext mappingContext) {
public RelationalConverter relationalConverter(RelationalMappingContext mappingContext) {
return super.relationalConverter(mappingContext);
}

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");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
*
* @author Andy Wilkinson
*/
class JdbcRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class JdbcRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

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");
* you may not use this file except in compliance with the License.
@@ -34,12 +34,10 @@ import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
* @since 1.1.0
* @see BeanDefinition#setDependsOn(String[])
*/
public class EntityManagerFactoryDependsOnPostProcessor
extends AbstractDependsOnBeanFactoryPostProcessor {
public class EntityManagerFactoryDependsOnPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor {
public EntityManagerFactoryDependsOnPostProcessor(String... dependsOn) {
super(EntityManagerFactory.class, AbstractEntityManagerFactoryBean.class,
dependsOn);
super(EntityManagerFactory.class, AbstractEntityManagerFactoryBean.class, dependsOn);
}
}

View File

@@ -62,13 +62,11 @@ import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
@Configuration
@ConditionalOnBean(DataSource.class)
@ConditionalOnClass(JpaRepository.class)
@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class,
JpaRepositoryConfigExtension.class })
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class, JpaRepositoryConfigExtension.class })
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@Import(JpaRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter({ HibernateJpaAutoConfiguration.class,
TaskExecutionAutoConfiguration.class })
@AutoConfigureAfter({ HibernateJpaAutoConfiguration.class, TaskExecutionAutoConfiguration.class })
public class JpaRepositoriesAutoConfiguration {
@Bean
@@ -76,21 +74,18 @@ public class JpaRepositoriesAutoConfiguration {
public EntityManagerFactoryBuilderCustomizer entityManagerFactoryBootstrapExecutorCustomizer(
Map<String, AsyncTaskExecutor> taskExecutors) {
return (builder) -> {
AsyncTaskExecutor bootstrapExecutor = determineBootstrapExecutor(
taskExecutors);
AsyncTaskExecutor bootstrapExecutor = determineBootstrapExecutor(taskExecutors);
if (bootstrapExecutor != null) {
builder.setBootstrapExecutor(bootstrapExecutor);
}
};
}
private AsyncTaskExecutor determineBootstrapExecutor(
Map<String, AsyncTaskExecutor> taskExecutors) {
private AsyncTaskExecutor determineBootstrapExecutor(Map<String, AsyncTaskExecutor> taskExecutors) {
if (taskExecutors.size() == 1) {
return taskExecutors.values().iterator().next();
}
return taskExecutors
.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME);
return taskExecutors.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME);
}
private static final class BootstrapExecutorCondition extends AnyNestedCondition {
@@ -99,14 +94,14 @@ public class JpaRepositoriesAutoConfiguration {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories",
name = "bootstrap-mode", havingValue = "deferred", matchIfMissing = false)
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "bootstrap-mode",
havingValue = "deferred", matchIfMissing = false)
static class DeferredBootstrapMode {
}
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories",
name = "bootstrap-mode", havingValue = "lazy", matchIfMissing = false)
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "bootstrap-mode", havingValue = "lazy",
matchIfMissing = false)
static class LazyBootstrapMode {
}

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");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ import org.springframework.util.StringUtils;
* @author Phillip Webb
* @author Dave Syer
*/
class JpaRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class JpaRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport {
private BootstrapMode bootstrapMode = null;
@@ -57,8 +56,7 @@ class JpaRepositoriesAutoConfigureRegistrar
@Override
protected BootstrapMode getBootstrapMode() {
return (this.bootstrapMode == null) ? super.getBootstrapMode()
: this.bootstrapMode;
return (this.bootstrapMode == null) ? super.getBootstrapMode() : this.bootstrapMode;
}
@Override
@@ -68,11 +66,9 @@ class JpaRepositoriesAutoConfigureRegistrar
}
private void configureBootstrapMode(Environment environment) {
String property = environment
.getProperty("spring.data.jpa.repositories.bootstrap-mode");
String property = environment.getProperty("spring.data.jpa.repositories.bootstrap-mode");
if (StringUtils.hasText(property)) {
this.bootstrapMode = BootstrapMode
.valueOf(property.toUpperCase(Locale.ENGLISH));
this.bootstrapMode = BootstrapMode.valueOf(property.toUpperCase(Locale.ENGLISH));
}
}

View File

@@ -35,8 +35,8 @@ import org.springframework.data.ldap.repository.support.LdapRepositoryFactoryBea
*/
@Configuration
@ConditionalOnClass({ LdapContext.class, LdapRepository.class })
@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.ldap.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnMissingBean(LdapRepositoryFactoryBean.class)
@Import(LdapRepositoriesRegistrar.class)
public class LdapRepositoriesAutoConfiguration {

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");
* you may not use this file except in compliance with the License.
@@ -34,8 +34,7 @@ import org.springframework.data.mongodb.core.MongoClientFactoryBean;
* @since 1.3.0
*/
@Order(Ordered.LOWEST_PRECEDENCE)
public class MongoClientDependsOnBeanFactoryPostProcessor
extends AbstractDependsOnBeanFactoryPostProcessor {
public class MongoClientDependsOnBeanFactoryPostProcessor extends AbstractDependsOnBeanFactoryPostProcessor {
public MongoClientDependsOnBeanFactoryPostProcessor(String... dependsOn) {
super(MongoClient.class, MongoClientFactoryBean.class, dependsOn);

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");
* you may not use this file except in compliance with the License.
@@ -73,8 +73,7 @@ import org.springframework.util.StringUtils;
* @since 1.1.0
*/
@Configuration
@ConditionalOnClass({ MongoClient.class, com.mongodb.client.MongoClient.class,
MongoTemplate.class })
@ConditionalOnClass({ MongoClient.class, com.mongodb.client.MongoClient.class, MongoTemplate.class })
@Conditional(AnyMongoClientAvailable.class)
@EnableConfigurationProperties(MongoProperties.class)
@Import(MongoDataConfiguration.class)
@@ -93,41 +92,35 @@ public class MongoDataAutoConfiguration {
ObjectProvider<com.mongodb.client.MongoClient> mongoClient) {
MongoClient preferredClient = mongo.getIfAvailable();
if (preferredClient != null) {
return new SimpleMongoDbFactory(preferredClient,
this.properties.getMongoClientDatabase());
return new SimpleMongoDbFactory(preferredClient, this.properties.getMongoClientDatabase());
}
com.mongodb.client.MongoClient fallbackClient = mongoClient.getIfAvailable();
if (fallbackClient != null) {
return new SimpleMongoClientDbFactory(fallbackClient,
this.properties.getMongoClientDatabase());
return new SimpleMongoClientDbFactory(fallbackClient, this.properties.getMongoClientDatabase());
}
throw new IllegalStateException("Expected to find at least one MongoDB client.");
}
@Bean
@ConditionalOnMissingBean
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory,
MongoConverter converter) {
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter converter) {
return new MongoTemplate(mongoDbFactory, converter);
}
@Bean
@ConditionalOnMissingBean(MongoConverter.class)
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
MongoMappingContext context, MongoCustomConversions conversions) {
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,
MongoCustomConversions conversions) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver,
context);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
mappingConverter.setCustomConversions(conversions);
return mappingConverter;
}
@Bean
@ConditionalOnMissingBean
public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory,
MongoTemplate mongoTemplate) {
return new GridFsTemplate(
new GridFsMongoDbFactory(mongoDbFactory, this.properties),
public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate) {
return new GridFsTemplate(new GridFsMongoDbFactory(mongoDbFactory, this.properties),
mongoTemplate.getConverter());
}

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");
* you may not use this file except in compliance with the License.
@@ -42,23 +42,19 @@ class MongoDataConfiguration {
private final MongoProperties properties;
MongoDataConfiguration(ApplicationContext applicationContext,
MongoProperties properties) {
MongoDataConfiguration(ApplicationContext applicationContext, MongoProperties properties) {
this.applicationContext = applicationContext;
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions)
throws ClassNotFoundException {
public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions) throws ClassNotFoundException {
MongoMappingContext context = new MongoMappingContext();
context.setInitialEntitySet(new EntityScanner(this.applicationContext)
.scan(Document.class, Persistent.class));
context.setInitialEntitySet(new EntityScanner(this.applicationContext).scan(Document.class, Persistent.class));
Class<?> strategyClass = this.properties.getFieldNamingStrategy();
if (strategyClass != null) {
context.setFieldNamingStrategy(
(FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass));
context.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass));
}
context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
return context;

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");
* you may not use this file except in compliance with the License.
@@ -67,16 +67,14 @@ public class MongoReactiveDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean(ReactiveMongoDatabaseFactory.class)
public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory(
MongoClient mongo) {
public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory(MongoClient mongo) {
String database = this.properties.getMongoClientDatabase();
return new SimpleReactiveMongoDatabaseFactory(mongo, database);
}
@Bean
@ConditionalOnMissingBean
public ReactiveMongoTemplate reactiveMongoTemplate(
ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory,
public ReactiveMongoTemplate reactiveMongoTemplate(ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory,
MongoConverter converter) {
return new ReactiveMongoTemplate(reactiveMongoDatabaseFactory, converter);
}
@@ -85,8 +83,7 @@ public class MongoReactiveDataAutoConfiguration {
@ConditionalOnMissingBean(MongoConverter.class)
public MappingMongoConverter mappingMongoConverter(MongoMappingContext context,
MongoCustomConversions conversions) {
MappingMongoConverter mappingConverter = new MappingMongoConverter(
NoOpDbRefResolver.INSTANCE, context);
MappingMongoConverter mappingConverter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, context);
mappingConverter.setCustomConversions(conversions);
return mappingConverter;
}

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