Merge branch '1.5.x' into 2.0.x

This commit is contained in:
Andy Wilkinson
2019-06-07 10:46:31 +01:00
2320 changed files with 23858 additions and 39476 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-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.
@@ -53,7 +53,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.
@@ -66,14 +66,12 @@ 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 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";
@@ -93,8 +91,7 @@ public class AutoConfigurationImportSelector
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
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);
@@ -111,9 +108,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;
}
@@ -127,12 +122,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;
}
@@ -153,13 +145,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;
}
@@ -172,12 +162,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);
}
}
@@ -196,9 +184,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));
}
/**
@@ -208,8 +196,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")));
@@ -220,16 +207,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];
@@ -256,15 +241,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) {
@@ -276,12 +259,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);
@@ -290,15 +271,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);
@@ -354,8 +333,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 ClassLoader beanClassLoader;
@@ -381,8 +360,7 @@ public class AutoConfigurationImportSelector
}
@Override
public void process(AnnotationMetadata annotationMetadata,
DeferredImportSelector deferredImportSelector) {
public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
String[] imports = deferredImportSelector.selectImports(annotationMetadata);
for (String importClassName : imports) {
this.entries.put(importClassName, annotationMetadata);
@@ -392,8 +370,7 @@ public class AutoConfigurationImportSelector
@Override
public Iterable<Entry> selectImports() {
return sortAutoConfigurations().stream()
.map((importClassName) -> new Entry(this.entries.get(importClassName),
importClassName))
.map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
.collect(Collectors.toList());
}
@@ -404,14 +381,13 @@ public class AutoConfigurationImportSelector
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
return new AutoConfigurationSorter(getMetadataReaderFactory(),
autoConfigurationMetadata).getInPriorityOrder(autoConfigurations);
return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata)
.getInPriorityOrder(autoConfigurations);
}
private MetadataReaderFactory getMetadataReaderFactory() {
try {
return this.beanFactory.getBean(
SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
return this.beanFactory.getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
MetadataReaderFactory.class);
}
catch (NoSuchBeanDefinitionException 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.
@@ -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-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.
@@ -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.toCollection(ArrayList::new));
List<String> names = classes.stream().map(Class::getName).collect(Collectors.toCollection(ArrayList::new));
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.
@@ -45,22 +45,18 @@ 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> {
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 (event instanceof ApplicationStartingEvent
&& preinitializationStarted.compareAndSet(false, true)) {
if (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-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.
@@ -54,8 +54,7 @@ class SharedMetadataReaderFactoryContextInitializer
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.addBeanFactoryPostProcessor(
new CachingMetadataReaderFactoryPostProcessor());
applicationContext.addBeanFactoryPostProcessor(new CachingMetadataReaderFactoryPostProcessor());
}
/**
@@ -73,30 +72,25 @@ class SharedMetadataReaderFactoryContextInitializer
}
@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) {
RootBeanDefinition definition = new RootBeanDefinition(
SharedMetadataReaderFactoryBean.class);
RootBeanDefinition definition = new RootBeanDefinition(SharedMetadataReaderFactoryBean.class);
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) {
}
@@ -108,20 +102,18 @@ class SharedMetadataReaderFactoryContextInitializer
* {@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

@@ -43,8 +43,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 {
/**
@@ -62,18 +62,16 @@ public class SpringApplicationAdminJmxAutoConfiguration {
private final Environment environment;
public SpringApplicationAdminJmxAutoConfiguration(
ObjectProvider<List<MBeanExporter>> mbeanExporters, Environment environment) {
public SpringApplicationAdminJmxAutoConfiguration(ObjectProvider<List<MBeanExporter>> mbeanExporters,
Environment environment) {
this.mbeanExporters = mbeanExporters.getIfAvailable();
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.
@@ -104,14 +104,13 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer<T extends
}
ListenerRetry retryConfig = configuration.getRetry();
if (retryConfig.isEnabled()) {
RetryInterceptorBuilder<?> builder = (retryConfig.isStateless()
? RetryInterceptorBuilder.stateless()
RetryInterceptorBuilder<?> builder = (retryConfig.isStateless() ? RetryInterceptorBuilder.stateless()
: RetryInterceptorBuilder.stateful());
builder.maxAttempts(retryConfig.getMaxAttempts());
builder.backOffOptions(retryConfig.getInitialInterval().toMillis(),
retryConfig.getMultiplier(), retryConfig.getMaxInterval().toMillis());
MessageRecoverer recoverer = (this.messageRecoverer != null)
? this.messageRecoverer : new RejectAndDontRequeueRecoverer();
builder.backOffOptions(retryConfig.getInitialInterval().toMillis(), retryConfig.getMultiplier(),
retryConfig.getMaxInterval().toMillis());
MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer
: new RejectAndDontRequeueRecoverer();
builder.recoverer(recoverer);
factory.setAdviceChain(builder.build());
}

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,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

@@ -48,8 +48,7 @@ class RabbitAnnotationDrivenConfiguration {
private final RabbitProperties properties;
RabbitAnnotationDrivenConfiguration(ObjectProvider<MessageConverter> messageConverter,
ObjectProvider<MessageRecoverer> messageRecoverer,
RabbitProperties properties) {
ObjectProvider<MessageRecoverer> messageRecoverer, RabbitProperties properties) {
this.messageConverter = messageConverter;
this.messageRecoverer = messageRecoverer;
this.properties = properties;
@@ -67,11 +66,10 @@ class RabbitAnnotationDrivenConfiguration {
@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;
@@ -89,11 +87,9 @@ class RabbitAnnotationDrivenConfiguration {
@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;
@@ -101,8 +97,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

@@ -96,14 +96,11 @@ public class RabbitAutoConfiguration {
// Only available in rabbitmq-java-client 5.4.0 +
private static final boolean CAN_ENABLE_HOSTNAME_VERIFICATION = ReflectionUtils
.findMethod(com.rabbitmq.client.ConnectionFactory.class,
"enableHostnameVerification") != null;
.findMethod(com.rabbitmq.client.ConnectionFactory.class, "enableHostnameVerification") != null;
@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());
@@ -114,30 +111,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);
@@ -148,16 +139,15 @@ 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).when(Objects::nonNull)
.to(factory::setEnableHostnameVerification);
map.from(ssl::isValidateServerCertificate)
.to((validate) -> factory.setSkipServerCertificateValidation(!validate));
map.from(ssl::getVerifyHostname).when(Objects::nonNull).to(factory::setEnableHostnameVerification);
if (ssl.getVerifyHostname() == null && CAN_ENABLE_HOSTNAME_VERIFICATION) {
factory.setEnableHostnameVerification(true);
}
}
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;
}
@@ -172,8 +162,7 @@ public class RabbitAutoConfiguration {
private final RabbitProperties properties;
public RabbitTemplateConfiguration(
ObjectProvider<MessageConverter> messageConverter,
public RabbitTemplateConfiguration(ObjectProvider<MessageConverter> messageConverter,
RabbitProperties properties) {
this.messageConverter = messageConverter;
this.properties = properties;
@@ -196,8 +185,7 @@ public class RabbitAutoConfiguration {
}
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);
return template;
@@ -218,16 +206,14 @@ public class RabbitAutoConfiguration {
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);
return template;
}
@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);
@@ -243,8 +229,7 @@ public class RabbitAutoConfiguration {
@Bean
@ConditionalOnSingleCandidate(RabbitTemplate.class)
public RabbitMessagingTemplate rabbitMessagingTemplate(
RabbitTemplate rabbitTemplate) {
public RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) {
return new RabbitMessagingTemplate(rabbitTemplate);
}

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,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-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.
@@ -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

@@ -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,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.
@@ -72,16 +72,15 @@ public class CacheAutoConfiguration {
}
@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");
@@ -99,8 +98,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;
}
@@ -108,8 +106,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-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.
@@ -43,8 +43,7 @@ class HazelcastJCacheCustomizationConfiguration {
return new HazelcastPropertiesCustomizer(hazelcastInstance.getIfUnique());
}
private static class HazelcastPropertiesCustomizer
implements JCachePropertiesCustomizer {
private static class HazelcastPropertiesCustomizer implements JCachePropertiesCustomizer {
private final HazelcastInstance hazelcastInstance;
@@ -54,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);
@@ -71,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.
@@ -59,8 +59,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 {
@@ -76,8 +75,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<List<JCacheManagerCustomizer>> cacheManagerCustomizers,
ObjectProvider<List<JCachePropertiesCustomizer>> cachePropertiesCustomizers) {
@@ -114,14 +112,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);
}
@@ -192,28 +188,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,24 +64,21 @@ 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((list) -> StringUtils.toStringArray(list))
map.from(properties::getContactPoints).as((list) -> StringUtils.toStringArray(list))
.to(builder::addContactPoints);
customize(builder);
return builder.build();
@@ -99,10 +96,8 @@ public class CassandraAutoConfiguration {
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;
}
@@ -110,8 +105,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;
@@ -123,10 +118,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

@@ -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 @@ 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.
@@ -192,8 +191,7 @@ public class CassandraProperties {
return this.loadBalancingPolicy;
}
public void setLoadBalancingPolicy(
Class<? extends LoadBalancingPolicy> loadBalancingPolicy) {
public void setLoadBalancingPolicy(Class<? extends LoadBalancingPolicy> loadBalancingPolicy) {
this.loadBalancingPolicy = loadBalancingPolicy;
}
@@ -225,8 +223,7 @@ public class CassandraProperties {
return this.reconnectionPolicy;
}
public void setReconnectionPolicy(
Class<? extends ReconnectionPolicy> reconnectionPolicy) {
public void setReconnectionPolicy(Class<? extends ReconnectionPolicy> reconnectionPolicy) {
this.reconnectionPolicy = reconnectionPolicy;
}

View File

@@ -50,8 +50,7 @@ import org.springframework.core.Ordered;
@AutoConfigureOrder(CloudAutoConfiguration.ORDER)
@ConditionalOnClass(CloudScanConfiguration.class)
@ConditionalOnMissingBean(Cloud.class)
@ConditionalOnProperty(prefix = "spring.cloud", name = "enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.cloud", name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(CloudScanConfiguration.class)
public class CloudAutoConfiguration {

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.
@@ -90,8 +90,7 @@ 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 bd = new RootBeanDefinition(BeanTypeRegistry.class);
bd.getConstructorArgumentValues().addIndexedArgumentValue(0, beanFactory);
@@ -112,10 +111,8 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
Set<String> getNamesForType(Class<?> type) {
updateTypesIfNecessary();
return this.beanTypes.entrySet().stream()
.filter((entry) -> entry.getValue() != null
&& type.isAssignableFrom(entry.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
.filter((entry) -> entry.getValue() != null && type.isAssignableFrom(entry.getValue()))
.map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
@@ -130,10 +127,9 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
Set<String> getNamesForAnnotation(Class<? extends Annotation> annotation) {
updateTypesIfNecessary();
return this.beanTypes.entrySet().stream()
.filter((entry) -> entry.getValue() != null && AnnotationUtils
.findAnnotation(entry.getValue(), annotation) != null)
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
.filter((entry) -> entry.getValue() != null
&& AnnotationUtils.findAnnotation(entry.getValue(), annotation) != null)
.map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new));
}
@Override
@@ -184,18 +180,14 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
}
}
private void addBeanTypeForNonAliasDefinition(String name,
RootBeanDefinition beanDefinition) {
private void addBeanTypeForNonAliasDefinition(String name, RootBeanDefinition beanDefinition) {
try {
if (!beanDefinition.isAbstract()
&& !requiresEagerInit(beanDefinition.getFactoryBeanName())) {
if (!beanDefinition.isAbstract() && !requiresEagerInit(beanDefinition.getFactoryBeanName())) {
String factoryName = BeanFactory.FACTORY_BEAN_PREFIX + name;
if (this.beanFactory.isFactoryBean(factoryName)) {
Class<?> factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory,
beanDefinition);
Class<?> factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, beanDefinition);
this.beanTypes.put(name, factoryBeanGeneric);
this.beanTypes.put(factoryName,
this.beanFactory.getType(factoryName));
this.beanTypes.put(factoryName, this.beanFactory.getType(factoryName));
}
else {
this.beanTypes.put(name, this.beanFactory.getType(name));
@@ -237,8 +229,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
* @param definition the bean definition
* @return the generic type of the {@link FactoryBean} or {@code null}
*/
private Class<?> getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory,
BeanDefinition definition) {
private Class<?> getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) {
try {
return doGetFactoryBeanGeneric(beanFactory, definition);
}
@@ -247,8 +238,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
}
}
private Class<?> doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory,
BeanDefinition definition)
private Class<?> doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
throws Exception, ClassNotFoundException, LinkageError {
if (StringUtils.hasLength(definition.getFactoryBeanName())
&& StringUtils.hasLength(definition.getFactoryMethodName())) {
@@ -260,32 +250,25 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
return null;
}
private Class<?> getConfigurationClassFactoryBeanGeneric(
ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
throws Exception {
private Class<?> getConfigurationClassFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory,
BeanDefinition definition) throws Exception {
Method method = getFactoryMethod(beanFactory, definition);
Class<?> generic = ResolvableType.forMethodReturnType(method)
.as(FactoryBean.class).resolveGeneric();
if ((generic == null || generic.equals(Object.class))
&& definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(
definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
Class<?> generic = ResolvableType.forMethodReturnType(method).as(FactoryBean.class).resolveGeneric();
if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
}
return generic;
}
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);
@@ -306,10 +289,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());
}
@@ -322,23 +303,17 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
return Arrays.equals(candidate.getParameterTypes(), current.getParameterTypes());
}
private Class<?> getDirectFactoryBeanGeneric(
ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
private Class<?> getDirectFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
throws ClassNotFoundException, LinkageError {
Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(),
beanFactory.getBeanClassLoader());
Class<?> generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class)
.resolveGeneric();
if ((generic == null || generic.equals(Object.class))
&& definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(
definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader());
Class<?> generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class).resolveGeneric();
if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) {
generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE));
}
return generic;
}
private Class<?> getTypeFromAttribute(Object attribute)
throws ClassNotFoundException, LinkageError {
private Class<?> getTypeFromAttribute(Object attribute) throws ClassNotFoundException, LinkageError {
if (attribute instanceof Class<?>) {
return (Class<?>) attribute;
}

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 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");
@@ -125,8 +124,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);
}
});
@@ -161,8 +160,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)) {
@@ -177,12 +175,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);
}
}
@@ -190,12 +185,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);
@@ -269,8 +261,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-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.
@@ -72,20 +72,17 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
}
@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())) {
@@ -93,50 +90,41 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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.namesOfAllMatches);
matchMessage = matchMessage.andCondition(ConditionalOnSingleCandidate.class, spec)
.found("a primary bean from beans").items(Style.QUOTE, matchResult.namesOfAllMatches);
}
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);
}
private String createOnBeanNoMatchReason(MatchResult matchResult) {
StringBuilder reason = new StringBuilder();
appendMessageForNoMatches(reason, matchResult.unmatchedAnnotations,
"annotated with");
appendMessageForNoMatches(reason, matchResult.unmatchedAnnotations, "annotated with");
appendMessageForNoMatches(reason, matchResult.unmatchedTypes, "of type");
appendMessageForNoMatches(reason, matchResult.unmatchedNames, "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 ");
@@ -157,14 +145,13 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
reason.append(" and ");
}
reason.append("found beans named ");
reason.append(StringUtils
.collectionToDelimitedString(matchResult.matchedNames, ", "));
reason.append(StringUtils.collectionToDelimitedString(matchResult.matchedNames, ", "));
}
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) {
@@ -184,17 +171,16 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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;
List<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(
beans.getIgnoredTypes(), beanFactory, context, considerHierarchy);
List<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(beans.getIgnoredTypes(), beanFactory, context,
considerHierarchy);
for (String type : beans.getTypes()) {
Collection<String> typeMatches = getBeanNamesForType(beanFactory, type,
context.getClassLoader(), considerHierarchy);
Collection<String> typeMatches = getBeanNamesForType(beanFactory, type, context.getClassLoader(),
considerHierarchy);
typeMatches.removeAll(beansIgnoredByType);
if (typeMatches.isEmpty()) {
matchResult.recordUnmatchedType(type);
@@ -204,9 +190,8 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
}
}
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);
@@ -216,8 +201,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
}
}
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 {
@@ -227,32 +211,29 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
return matchResult;
}
private List<String> getNamesOfBeansIgnoredByType(List<String> ignoredTypes,
ListableBeanFactory beanFactory, ConditionContext context,
boolean considerHierarchy) {
private List<String> getNamesOfBeansIgnoredByType(List<String> ignoredTypes, ListableBeanFactory beanFactory,
ConditionContext context, boolean considerHierarchy) {
List<String> beanNames = new ArrayList<>();
for (String ignoredType : ignoredTypes) {
beanNames.addAll(getBeanNamesForType(beanFactory, ignoredType,
context.getClassLoader(), considerHierarchy));
beanNames
.addAll(getBeanNamesForType(beanFactory, ignoredType, 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, ClassLoader classLoader, boolean considerHierarchy)
throws LinkageError {
private Collection<String> getBeanNamesForType(ListableBeanFactory beanFactory, String type,
ClassLoader classLoader, boolean considerHierarchy) throws LinkageError {
try {
Set<String> result = new LinkedHashSet<>();
collectBeanNamesForType(result, beanFactory,
ClassUtils.forName(type, classLoader), considerHierarchy);
collectBeanNamesForType(result, beanFactory, ClassUtils.forName(type, classLoader), considerHierarchy);
return result;
}
catch (ClassNotFoundException | NoClassDefFoundError ex) {
@@ -260,29 +241,25 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
}
}
private void collectBeanNamesForType(Set<String> result,
ListableBeanFactory beanFactory, Class<?> type, boolean considerHierarchy) {
private void collectBeanNamesForType(Set<String> result, ListableBeanFactory beanFactory, Class<?> type,
boolean considerHierarchy) {
result.addAll(BeanTypeRegistry.get(beanFactory).getNamesForType(type));
if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory) {
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory)
.getParentBeanFactory();
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory();
if (parent instanceof ListableBeanFactory) {
collectBeanNamesForType(result, (ListableBeanFactory) parent, type,
considerHierarchy);
collectBeanNamesForType(result, (ListableBeanFactory) parent, type, considerHierarchy);
}
}
}
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
@@ -290,35 +267,27 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
return StringUtils.toStringArray(names);
}
private void collectBeanNamesForAnnotation(Set<String> names,
ListableBeanFactory beanFactory, Class<? extends Annotation> annotationType,
boolean considerHierarchy) {
names.addAll(
BeanTypeRegistry.get(beanFactory).getNamesForAnnotation(annotationType));
private void collectBeanNamesForAnnotation(Set<String> names, ListableBeanFactory beanFactory,
Class<? extends Annotation> annotationType, boolean considerHierarchy) {
names.addAll(BeanTypeRegistry.get(beanFactory).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 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);
}
@@ -326,15 +295,14 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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;
@@ -354,19 +322,17 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
private final SearchStrategy strategy;
BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata,
Class<?> annotationType) {
BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class<?> annotationType) {
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);
collect(attributes, "annotation", this.annotations);
collect(attributes, "ignored", this.ignoredTypes);
collect(attributes, "ignoredType", this.ignoredTypes);
this.strategy = (SearchStrategy) metadata
.getAnnotationAttributes(annotationType.getName()).get("search");
this.strategy = (SearchStrategy) metadata.getAnnotationAttributes(annotationType.getName()).get("search");
BeanTypeDeductionException deductionException = null;
try {
if (this.types.isEmpty() && this.names.isEmpty()) {
@@ -381,13 +347,11 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
protected void validate(BeanTypeDeductionException ex) {
if (!hasAtLeastOne(this.types, this.names, this.annotations)) {
String message = annotationName()
+ " did not specify a bean using type, name or annotation";
String message = annotationName() + " 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);
}
}
@@ -404,8 +368,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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) {
@@ -419,27 +382,23 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
}
}
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 {
// We should be safe to load at this point since we are in the
// REGISTER_BEAN phase
Class<?> returnType = ClassUtils.forName(metadata.getReturnTypeName(),
context.getClassLoader());
Class<?> returnType = ClassUtils.forName(metadata.getReturnTypeName(), context.getClassLoader());
beanTypes.add(returnType.getName());
}
catch (Throwable ex) {
throw new BeanTypeDeductionException(metadata.getDeclaringClassName(),
metadata.getMethodName(), ex);
throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), metadata.getMethodName(), ex);
}
}
@@ -488,32 +447,29 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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, () -> annotationName()
+ " annotations must specify only one type (got " + getTypes() + ")");
Assert.isTrue(getTypes().size() == 1,
() -> annotationName() + " annotations must specify only one type (got " + getTypes() + ")");
}
}
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);
}
}
@@ -543,8 +499,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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);
}

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.
@@ -57,19 +57,16 @@ class OnClassCondition extends SpringBootCondition
private ClassLoader beanClassLoader;
@Override
public boolean[] match(String[] autoConfigurationClasses,
AutoConfigurationMetadata autoConfigurationMetadata) {
public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
ConditionEvaluationReport report = getConditionEvaluationReport();
ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses,
autoConfigurationMetadata);
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]);
}
}
}
@@ -77,10 +74,8 @@ class OnClassCondition extends SpringBootCondition
}
private ConditionEvaluationReport getConditionEvaluationReport() {
if (this.beanFactory != null
&& this.beanFactory instanceof ConfigurableBeanFactory) {
return ConditionEvaluationReport
.get((ConfigurableListableBeanFactory) this.beanFactory);
if (this.beanFactory != null && this.beanFactory instanceof ConfigurableBeanFactory) {
return ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory);
}
return null;
}
@@ -91,11 +86,10 @@ class OnClassCondition extends SpringBootCondition
// 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, this.beanClassLoader);
OutcomesResolver firstHalfResolver = createOutcomesResolver(autoConfigurationClasses, 0, split,
autoConfigurationMetadata);
OutcomesResolver secondHalfResolver = new StandardOutcomesResolver(autoConfigurationClasses, split,
autoConfigurationClasses.length, autoConfigurationMetadata, this.beanClassLoader);
ConditionOutcome[] secondHalf = secondHalfResolver.resolveOutcomes();
ConditionOutcome[] firstHalf = firstHalfResolver.resolveOutcomes();
ConditionOutcome[] outcomes = new ConditionOutcome[autoConfigurationClasses.length];
@@ -104,11 +98,10 @@ class OnClassCondition extends SpringBootCondition
return outcomes;
}
private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses,
int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) {
OutcomesResolver outcomesResolver = new StandardOutcomesResolver(
autoConfigurationClasses, start, end, autoConfigurationMetadata,
this.beanClassLoader);
private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, int start, int end,
AutoConfigurationMetadata autoConfigurationMetadata) {
OutcomesResolver outcomesResolver = new StandardOutcomesResolver(autoConfigurationClasses, start, end,
autoConfigurationMetadata, this.beanClassLoader);
try {
return new ThreadedOutcomesResolver(outcomesResolver);
}
@@ -118,45 +111,36 @@ class OnClassCondition extends SpringBootCondition
}
@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 = getMatches(onClasses, MatchType.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,
getMatches(onClasses, MatchType.PRESENT, classLoader));
.found("required class", "required classes")
.items(Style.QUOTE, getMatches(onClasses, MatchType.PRESENT, classLoader));
}
List<String> onMissingClasses = getCandidates(metadata,
ConditionalOnMissingClass.class);
List<String> onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class);
if (onMissingClasses != null) {
List<String> present = getMatches(onMissingClasses, MatchType.PRESENT,
classLoader);
List<String> present = getMatches(onMissingClasses, MatchType.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,
getMatches(onMissingClasses, MatchType.MISSING, classLoader));
.didNotFind("unwanted class", "unwanted classes")
.items(Style.QUOTE, getMatches(onMissingClasses, MatchType.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 Collections.emptyList();
}
@@ -174,8 +158,7 @@ class OnClassCondition extends SpringBootCondition
}
}
private List<String> getMatches(Collection<String> candidates, MatchType matchType,
ClassLoader classLoader) {
private List<String> getMatches(Collection<String> candidates, MatchType matchType, ClassLoader classLoader) {
List<String> matches = new ArrayList<>(candidates.size());
for (String candidate : candidates) {
if (matchType.matches(candidate, classLoader)) {
@@ -228,8 +211,7 @@ class OnClassCondition 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);
}
@@ -253,8 +235,7 @@ class OnClassCondition extends SpringBootCondition
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();
}
@@ -283,9 +264,8 @@ class OnClassCondition extends SpringBootCondition
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;
@@ -295,17 +275,15 @@ class OnClassCondition extends SpringBootCondition
@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];
Set<String> candidates = autoConfigurationMetadata
.getSet(autoConfigurationClass, "ConditionalOnClass");
Set<String> candidates = autoConfigurationMetadata.getSet(autoConfigurationClass, "ConditionalOnClass");
if (candidates != null) {
outcomes[i - start] = getOutcome(candidates);
}
@@ -315,13 +293,10 @@ class OnClassCondition extends SpringBootCondition
private ConditionOutcome getOutcome(Set<String> candidates) {
try {
List<String> missing = getMatches(candidates, MatchType.MISSING,
this.beanClassLoader);
List<String> missing = getMatches(candidates, MatchType.MISSING, this.beanClassLoader);
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));
}
}
catch (Exception 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.
@@ -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.
@@ -46,10 +46,8 @@ class OnWebApplicationCondition extends SpringBootCondition {
+ "support.GenericWebApplicationContext";
@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());
@@ -60,8 +58,8 @@ class OnWebApplicationCondition extends SpringBootCondition {
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);
@@ -72,30 +70,25 @@ class OnWebApplicationCondition extends SpringBootCondition {
}
}
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 (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) {
return ConditionOutcome
.noMatch(message.didNotFind("web application classes").atAll());
return ConditionOutcome.noMatch(message.didNotFind("web application classes").atAll());
}
if (context.getBeanFactory() != null) {
String[] scopes = context.getBeanFactory().getRegisteredScopeNames();
@@ -104,8 +97,7 @@ class OnWebApplicationCondition extends SpringBootCondition {
}
}
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"));
@@ -116,20 +108,16 @@ class OnWebApplicationCondition extends SpringBootCondition {
private ConditionOutcome isReactiveWebApplication(ConditionContext context) {
ConditionMessage.Builder message = ConditionMessage.forCondition("");
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.
@@ -68,8 +68,8 @@ public class MessageSourceAutoConfiguration {
MessageSourceProperties properties = messageSourceProperties();
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());
@@ -89,10 +89,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);
@@ -101,21 +99,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

@@ -76,8 +76,7 @@ public class CouchbaseAutoConfiguration {
@Bean
@Primary
public Cluster couchbaseCluster() throws Exception {
return CouchbaseCluster.create(couchbaseEnvironment(),
this.properties.getBootstrapHosts());
return CouchbaseCluster.create(couchbaseEnvironment(), this.properties.getBootstrapHosts());
}
@Bean
@@ -85,8 +84,7 @@ public class CouchbaseAutoConfiguration {
@DependsOn("couchbaseClient")
public ClusterInfo couchbaseClusterInfo() throws Exception {
return couchbaseCluster()
.clusterManager(this.properties.getBucket().getName(),
this.properties.getBucket().getPassword())
.clusterManager(this.properties.getBucket().getName(), this.properties.getBucket().getPassword())
.info();
}
@@ -102,17 +100,14 @@ public class CouchbaseAutoConfiguration {
* @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());
}
@@ -122,8 +117,7 @@ public class CouchbaseAutoConfiguration {
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());
@@ -143,21 +137,18 @@ public class CouchbaseAutoConfiguration {
@SuppressWarnings("deprecation")
private QueryServiceConfig getQueryServiceConfig(Endpoints endpoints) {
return getServiceConfig(endpoints.getQueryservice(), endpoints.getQuery(),
QueryServiceConfig::create);
return getServiceConfig(endpoints.getQueryservice(), endpoints.getQuery(), QueryServiceConfig::create);
}
@SuppressWarnings("deprecation")
private ViewServiceConfig getViewServiceConfig(Endpoints endpoints) {
return getServiceConfig(endpoints.getViewservice(), endpoints.getView(),
ViewServiceConfig::create);
return getServiceConfig(endpoints.getViewservice(), endpoints.getView(), ViewServiceConfig::create);
}
private <T> T getServiceConfig(CouchbaseService service, Integer fallback,
BiFunction<Integer, Integer, T> factory) {
if (service.getMinEndpoints() != 1 || service.getMaxEndpoints() != 1) {
return factory.apply(service.getMinEndpoints(),
service.getMaxEndpoints());
return factory.apply(service.getMinEndpoints(), service.getMaxEndpoints());
}
int endpoints = (fallback != null) ? fallback : 1;
return factory.apply(endpoints, endpoints);
@@ -184,8 +175,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

@@ -147,8 +147,7 @@ public class CouchbaseProperties {
}
@Deprecated
@DeprecatedConfigurationProperty(
replacement = "spring.couchbase.env.endpoints.queryservice.max-endpoints")
@DeprecatedConfigurationProperty(replacement = "spring.couchbase.env.endpoints.queryservice.max-endpoints")
public Integer getQuery() {
return this.query;
}
@@ -163,8 +162,7 @@ public class CouchbaseProperties {
}
@Deprecated
@DeprecatedConfigurationProperty(
replacement = "spring.couchbase.env.endpoints.viewservice.max-endpoints")
@DeprecatedConfigurationProperty(replacement = "spring.couchbase.env.endpoints.viewservice.max-endpoints")
public Integer getView() {
return this.view;
}
@@ -229,8 +227,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-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,8 +44,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;
@@ -54,23 +53,19 @@ 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();
}
};
}

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

@@ -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.
@@ -71,8 +71,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;
@@ -81,19 +81,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;
}
@@ -113,22 +112,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-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,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

@@ -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

@@ -54,10 +54,9 @@ 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)
public class JpaRepositoriesAutoConfiguration {

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 Phillip Webb
* @author Dave Syer
*/
class JpaRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class JpaRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

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.
@@ -79,8 +79,7 @@ public class MongoDataAutoConfiguration {
private final MongoProperties properties;
public MongoDataAutoConfiguration(ApplicationContext applicationContext,
MongoProperties properties) {
public MongoDataAutoConfiguration(ApplicationContext applicationContext, MongoProperties properties) {
this.applicationContext = applicationContext;
this.properties = properties;
}
@@ -94,33 +93,28 @@ public class MongoDataAutoConfiguration {
@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 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;
@@ -128,10 +122,8 @@ public class MongoDataAutoConfiguration {
@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.
@@ -48,8 +48,7 @@ import org.springframework.data.mongodb.core.convert.MongoConverter;
@Configuration
@ConditionalOnClass({ MongoClient.class, ReactiveMongoTemplate.class })
@EnableConfigurationProperties(MongoProperties.class)
@AutoConfigureAfter({ MongoReactiveAutoConfiguration.class,
MongoDataAutoConfiguration.class })
@AutoConfigureAfter({ MongoReactiveAutoConfiguration.class, MongoDataAutoConfiguration.class })
public class MongoReactiveDataAutoConfiguration {
private final MongoProperties properties;
@@ -60,16 +59,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);
}

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 Mark Paluch
* @since 2.0.0
*/
class MongoReactiveRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class MongoReactiveRepositoriesAutoConfigureRegistrar 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.
@@ -54,8 +54,7 @@ import org.springframework.data.mongodb.repository.support.MongoRepositoryFactor
*/
@Configuration
@ConditionalOnClass({ MongoClient.class, MongoRepository.class })
@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class,
MongoRepositoryConfigurationExtension.class })
@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, MongoRepositoryConfigurationExtension.class })
@ConditionalOnRepositoryType(store = "mongodb", type = RepositoryType.IMPERATIVE)
@Import(MongoRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter(MongoDataAutoConfiguration.class)

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 Dave Syer
*/
class MongoRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class MongoRepositoriesAutoConfigureRegistrar 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.
@@ -37,8 +37,7 @@ import org.springframework.data.mongodb.core.ReactiveMongoClientFactoryBean;
public class ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor
extends AbstractDependsOnBeanFactoryPostProcessor {
public ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor(
String... dependsOn) {
public ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor(String... dependsOn) {
super(MongoClient.class, ReactiveMongoClientFactoryBean.class, dependsOn);
}

View File

@@ -55,8 +55,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
* @since 1.4.0
*/
@Configuration
@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class,
PlatformTransactionManager.class })
@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, PlatformTransactionManager.class })
@ConditionalOnMissingBean(SessionFactory.class)
@EnableConfigurationProperties(Neo4jProperties.class)
public class Neo4jDataAutoConfiguration {
@@ -69,10 +68,8 @@ public class Neo4jDataAutoConfiguration {
@Bean
public SessionFactory sessionFactory(org.neo4j.ogm.config.Configuration configuration,
ApplicationContext applicationContext,
ObjectProvider<List<EventListener>> eventListeners) {
SessionFactory sessionFactory = new SessionFactory(configuration,
getPackagesToScan(applicationContext));
ApplicationContext applicationContext, ObjectProvider<List<EventListener>> eventListeners) {
SessionFactory sessionFactory = new SessionFactory(configuration, getPackagesToScan(applicationContext));
List<EventListener> providedEventListeners = eventListeners.getIfAvailable();
if (providedEventListeners != null) {
for (EventListener eventListener : providedEventListeners) {
@@ -84,11 +81,9 @@ public class Neo4jDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean(PlatformTransactionManager.class)
public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory,
Neo4jProperties properties,
public Neo4jTransactionManager transactionManager(SessionFactory sessionFactory, Neo4jProperties properties,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
return customize(new Neo4jTransactionManager(sessionFactory),
transactionManagerCustomizers.getIfAvailable());
return customize(new Neo4jTransactionManager(sessionFactory), transactionManagerCustomizers.getIfAvailable());
}
private Neo4jTransactionManager customize(Neo4jTransactionManager transactionManager,
@@ -100,8 +95,7 @@ public class Neo4jDataAutoConfiguration {
}
private String[] getPackagesToScan(ApplicationContext applicationContext) {
List<String> packages = EntityScanPackages.get(applicationContext)
.getPackageNames();
List<String> packages = EntityScanPackages.get(applicationContext).getPackageNames();
if (packages.isEmpty() && AutoConfigurationPackages.has(applicationContext)) {
packages = AutoConfigurationPackages.get(applicationContext);
}
@@ -112,15 +106,14 @@ public class Neo4jDataAutoConfiguration {
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ WebMvcConfigurer.class, OpenSessionInViewInterceptor.class })
@ConditionalOnMissingBean(OpenSessionInViewInterceptor.class)
@ConditionalOnProperty(prefix = "spring.data.neo4j", name = "open-in-view",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.neo4j", name = "open-in-view", havingValue = "true",
matchIfMissing = true)
protected static class Neo4jWebConfiguration {
@Configuration
protected static class Neo4jWebMvcConfiguration implements WebMvcConfigurer {
private static final Log logger = LogFactory
.getLog(Neo4jWebMvcConfiguration.class);
private static final Log logger = LogFactory.getLog(Neo4jWebMvcConfiguration.class);
private final Neo4jProperties neo4jProperties;

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.
@@ -149,8 +149,7 @@ public class Neo4jProperties implements ApplicationContextAware {
}
private void configureUriWithDefaults(Builder builder) {
if (!getEmbedded().isEnabled()
|| !ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) {
if (!getEmbedded().isEnabled() || !ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) {
builder.uri(DEFAULT_BOLT_URI);
}
}

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