Upgrade to spring-javaformat 0.0.11

This commit is contained in:
Andy Wilkinson
2019-06-07 09:44:58 +01:00
parent d548c5ed31
commit 8f1be4cded
1940 changed files with 16814 additions and 28498 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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 @@ public abstract class AbstractDatabaseInitializer {
private final ResourceLoader resourceLoader;
protected AbstractDatabaseInitializer(DataSource dataSource,
ResourceLoader resourceLoader) {
protected AbstractDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
Assert.notNull(dataSource, "DataSource must not be null");
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.dataSource = dataSource;
@@ -72,9 +71,8 @@ public abstract class AbstractDatabaseInitializer {
protected String getDatabaseName() {
try {
String productName = JdbcUtils.commonDatabaseName(JdbcUtils
.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName")
.toString());
String productName = JdbcUtils.commonDatabaseName(
JdbcUtils.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName").toString());
DatabaseDriver databaseDriver = DatabaseDriver.fromProductName(productName);
if (databaseDriver == DatabaseDriver.UNKNOWN) {
throw new IllegalStateException("Unable to detect database type");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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;
@@ -72,25 +71,23 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor
private Iterable<String> getBeanNames(ListableBeanFactory beanFactory) {
Set<String> names = new HashSet<String>();
names.addAll(Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
beanFactory, this.beanClass, true, false)));
for (String factoryBeanName : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
beanFactory, this.factoryBeanClass, true, false)) {
names.addAll(Arrays
.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, this.beanClass, 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-2016 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.
@@ -52,7 +52,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 ConfigurableListableBeanFactory beanFactory;
@@ -92,8 +90,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);
configurations = sort(configurations, autoConfigurationMetadata);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
@@ -121,11 +118,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;
}
@@ -146,13 +141,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;
}
@@ -165,12 +158,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<String>(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);
}
}
@@ -189,9 +180,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));
}
/**
@@ -201,8 +192,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<String>();
excluded.addAll(asList(attributes, "exclude"));
excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName")));
@@ -212,8 +202,7 @@ public class AutoConfigurationImportSelector
private List<String> getExcludeAutoConfigurationsProperty() {
if (getEnvironment() instanceof ConfigurableEnvironment) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
this.environment, "spring.autoconfigure.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(this.environment, "spring.autoconfigure.");
Map<String, Object> properties = resolver.getSubProperties("exclude");
if (properties.isEmpty()) {
return Collections.emptyList();
@@ -223,27 +212,25 @@ public class AutoConfigurationImportSelector
String name = entry.getKey();
Object value = entry.getValue();
if (name.isEmpty() || name.startsWith("[") && value != null) {
excludes.addAll(new HashSet<String>(Arrays.asList(StringUtils
.tokenizeToStringArray(String.valueOf(value), ","))));
excludes.addAll(new HashSet<String>(
Arrays.asList(StringUtils.tokenizeToStringArray(String.valueOf(value), ","))));
}
}
return excludes;
}
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(),
"spring.autoconfigure.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(), "spring.autoconfigure.");
String[] exclude = resolver.getProperty("exclude", String[].class);
return Arrays.asList((exclude != null) ? exclude : new String[0]);
}
private List<String> sort(List<String> configurations,
AutoConfigurationMetadata autoConfigurationMetadata) throws IOException {
configurations = new AutoConfigurationSorter(getMetadataReaderFactory(),
autoConfigurationMetadata).getInPriorityOrder(configurations);
private List<String> sort(List<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata)
throws IOException {
configurations = new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata)
.getInPriorityOrder(configurations);
return configurations;
}
private List<String> filter(List<String> configurations,
AutoConfigurationMetadata autoConfigurationMetadata) {
private List<String> filter(List<String> configurations, AutoConfigurationMetadata autoConfigurationMetadata) {
long startTime = System.nanoTime();
String[] candidates = configurations.toArray(new String[configurations.size()]);
boolean[] skip = new boolean[candidates.length];
@@ -270,21 +257,18 @@ 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<String>(result);
}
protected List<AutoConfigurationImportFilter> getAutoConfigurationImportFilters() {
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class,
this.beanClassLoader);
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader);
}
private MetadataReaderFactory getMetadataReaderFactory() {
try {
return getBeanFactory().getBean(
SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
return getBeanFactory().getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME,
MetadataReaderFactory.class);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -301,12 +285,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);
@@ -315,15 +297,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);

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.
@@ -75,8 +75,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");
}
}
@@ -94,25 +93,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<String>();
merged.addAll(Arrays.asList(existing));
merged.addAll(Arrays.asList(packageNames));
@@ -127,8 +121,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());
}
@@ -204,12 +197,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.
@@ -54,8 +54,8 @@ class AutoConfigurationSorter {
}
public List<String> getInPriorityOrder(Collection<String> classNames) {
final AutoConfigurationClasses classes = new AutoConfigurationClasses(
this.metadataReaderFactory, this.autoConfigurationMetadata, classNames);
final AutoConfigurationClasses classes = new AutoConfigurationClasses(this.metadataReaderFactory,
this.autoConfigurationMetadata, classNames);
List<String> orderedClassNames = new ArrayList<String>(classNames);
// Initially sort alphabetically
Collections.sort(orderedClassNames);
@@ -75,8 +75,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<String>(classNames);
Set<String> sorted = new LinkedHashSet<String>();
Set<String> processing = new LinkedHashSet<String>();
@@ -86,9 +85,8 @@ class AutoConfigurationSorter {
return new ArrayList<String>(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);
}
@@ -109,11 +107,10 @@ class AutoConfigurationSorter {
private final Map<String, AutoConfigurationClass> classes = new HashMap<String, AutoConfigurationClass>();
AutoConfigurationClasses(MetadataReaderFactory metadataReaderFactory,
AutoConfigurationMetadata autoConfigurationMetadata,
Collection<String> classNames) {
AutoConfigurationMetadata autoConfigurationMetadata, Collection<String> classNames) {
for (String className : classNames) {
this.classes.put(className, new AutoConfigurationClass(className,
metadataReaderFactory, autoConfigurationMetadata));
this.classes.put(className,
new AutoConfigurationClass(className, metadataReaderFactory, autoConfigurationMetadata));
}
}
@@ -124,8 +121,7 @@ class AutoConfigurationSorter {
public Set<String> getClassesRequestedAfter(String className) {
Set<String> rtn = new LinkedHashSet<String>();
rtn.addAll(get(className).getAfter());
for (Map.Entry<String, AutoConfigurationClass> entry : this.classes
.entrySet()) {
for (Map.Entry<String, AutoConfigurationClass> entry : this.classes.entrySet()) {
if (entry.getValue().getBefore().contains(className)) {
rtn.add(entry.getKey());
}
@@ -149,8 +145,7 @@ class AutoConfigurationSorter {
private final Set<String> after;
AutoConfigurationClass(String className,
MetadataReaderFactory metadataReaderFactory,
AutoConfigurationClass(String className, MetadataReaderFactory metadataReaderFactory,
AutoConfigurationMetadata autoConfigurationMetadata) {
this.className = className;
this.metadataReaderFactory = metadataReaderFactory;
@@ -169,34 +164,33 @@ class AutoConfigurationSorter {
private int getOrder() {
if (this.autoConfigurationMetadata.wasProcessed(this.className)) {
return this.autoConfigurationMetadata.getInteger(this.className,
"AutoConfigureOrder", Ordered.LOWEST_PRECEDENCE);
return this.autoConfigurationMetadata.getInteger(this.className, "AutoConfigureOrder",
Ordered.LOWEST_PRECEDENCE);
}
Map<String, Object> attributes = getAnnotationMetadata()
.getAnnotationAttributes(AutoConfigureOrder.class.getName());
return (attributes != null) ? (Integer) attributes.get("value")
: Ordered.LOWEST_PRECEDENCE;
return (attributes != null) ? (Integer) attributes.get("value") : Ordered.LOWEST_PRECEDENCE;
}
private Set<String> readBefore() {
if (this.autoConfigurationMetadata.wasProcessed(this.className)) {
return this.autoConfigurationMetadata.getSet(this.className,
"AutoConfigureBefore", Collections.<String>emptySet());
return this.autoConfigurationMetadata.getSet(this.className, "AutoConfigureBefore",
Collections.<String>emptySet());
}
return getAnnotationValue(AutoConfigureBefore.class);
}
private Set<String> readAfter() {
if (this.autoConfigurationMetadata.wasProcessed(this.className)) {
return this.autoConfigurationMetadata.getSet(this.className,
"AutoConfigureAfter", Collections.<String>emptySet());
return this.autoConfigurationMetadata.getSet(this.className, "AutoConfigureAfter",
Collections.<String>emptySet());
}
return getAnnotationValue(AutoConfigureAfter.class);
}
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();
}
@@ -209,13 +203,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-2016 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,11 +43,9 @@ 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);
@@ -58,8 +56,7 @@ public class BackgroundPreinitializer
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-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,15 +33,12 @@ import org.springframework.core.type.AnnotationMetadata;
* @see EnableAutoConfiguration
*/
@Deprecated
public class EnableAutoConfigurationImportSelector
extends AutoConfigurationImportSelector {
public class EnableAutoConfigurationImportSelector extends AutoConfigurationImportSelector {
@Override
protected boolean isEnabled(AnnotationMetadata metadata) {
if (getClass().equals(EnableAutoConfigurationImportSelector.class)) {
return getEnvironment().getProperty(
EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class,
true);
return getEnvironment().getProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class, true);
}
return 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.
@@ -45,8 +45,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;
@@ -71,8 +70,7 @@ 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<String>();
Map<Class<?>, List<Annotation>> annotations = getAnnotations(metadata);
for (Map.Entry<Class<?>, List<Annotation>> entry : annotations.entrySet()) {
@@ -81,17 +79,15 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec
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);
}
@@ -99,20 +95,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<String>();
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());
@@ -121,8 +113,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));
}
@@ -131,21 +122,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<?>, Annotation>();
Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), null);
collectAnnotations(source, annotations, new HashSet<Class<?>>());
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.
@@ -39,8 +39,7 @@ import org.springframework.core.type.AnnotationMetadata;
public class MessageSourceAutoConfiguration {
private static final String[] REPLACEMENT = {
"org.springframework.boot.autoconfigure.context."
+ "MessageSourceAutoConfiguration" };
"org.springframework.boot.autoconfigure.context." + "MessageSourceAutoConfiguration" };
static class Selector implements ImportSelector {

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,7 @@ import org.springframework.core.type.AnnotationMetadata;
public class PropertyPlaceholderAutoConfiguration {
private static final String[] REPLACEMENT = {
"org.springframework.boot.autoconfigure.context."
+ "PropertyPlaceholderAutoConfiguration" };
"org.springframework.boot.autoconfigure.context." + "PropertyPlaceholderAutoConfiguration" };
static class Selector implements ImportSelector {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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

@@ -46,8 +46,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;
@@ -66,16 +65,14 @@ class RabbitAnnotationDrivenConfiguration {
@Bean
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer,
ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
return factory;
}
@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

@@ -90,12 +90,10 @@ 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 config)
throws Exception {
public CachingConnectionFactory rabbitConnectionFactory(RabbitProperties config) throws Exception {
RabbitConnectionFactoryBean factory = new RabbitConnectionFactoryBean();
if (config.determineHost() != null) {
factory.setHost(config.determineHost());
@@ -123,8 +121,7 @@ public class RabbitAutoConfiguration {
factory.setKeyStorePassphrase(ssl.getKeyStorePassword());
factory.setTrustStore(ssl.getTrustStore());
factory.setTrustStorePassphrase(ssl.getTrustStorePassword());
factory.setSkipServerCertificateValidation(
!ssl.isValidateServerCertificate());
factory.setSkipServerCertificateValidation(!ssl.isValidateServerCertificate());
if (ssl.getVerifyHostname() != null) {
factory.setEnableHostnameVerification(ssl.getVerifyHostname());
}
@@ -138,26 +135,21 @@ public class RabbitAutoConfiguration {
factory.setConnectionTimeout(config.getConnectionTimeout());
}
factory.afterPropertiesSet();
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
factory.getObject());
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(factory.getObject());
connectionFactory.setAddresses(config.determineAddresses());
connectionFactory.setPublisherConfirms(config.isPublisherConfirms());
connectionFactory.setPublisherReturns(config.isPublisherReturns());
if (config.getCache().getChannel().getSize() != null) {
connectionFactory
.setChannelCacheSize(config.getCache().getChannel().getSize());
connectionFactory.setChannelCacheSize(config.getCache().getChannel().getSize());
}
if (config.getCache().getConnection().getMode() != null) {
connectionFactory
.setCacheMode(config.getCache().getConnection().getMode());
connectionFactory.setCacheMode(config.getCache().getConnection().getMode());
}
if (config.getCache().getConnection().getSize() != null) {
connectionFactory.setConnectionCacheSize(
config.getCache().getConnection().getSize());
connectionFactory.setConnectionCacheSize(config.getCache().getConnection().getSize());
}
if (config.getCache().getChannel().getCheckoutTimeout() != null) {
connectionFactory.setChannelCheckoutTimeout(
config.getCache().getChannel().getCheckoutTimeout());
connectionFactory.setChannelCheckoutTimeout(config.getCache().getChannel().getCheckoutTimeout());
}
return connectionFactory;
}
@@ -172,8 +164,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;
@@ -223,8 +214,7 @@ public class RabbitAutoConfiguration {
@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
@ConditionalOnMissingBean(AmqpAdmin.class)
public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
@@ -240,8 +230,7 @@ public class RabbitAutoConfiguration {
@Bean
@ConditionalOnSingleCandidate(RabbitTemplate.class)
public RabbitMessagingTemplate rabbitMessagingTemplate(
RabbitTemplate rabbitTemplate) {
public RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) {
return new RabbitMessagingTemplate(rabbitTemplate);
}

View File

@@ -497,8 +497,7 @@ public class RabbitProperties {
@NestedConfigurationProperty
private final AmqpContainer simple = new AmqpContainer();
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.auto-startup")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.auto-startup")
@Deprecated
public boolean isAutoStartup() {
return getSimple().isAutoStartup();
@@ -509,8 +508,7 @@ public class RabbitProperties {
getSimple().setAutoStartup(autoStartup);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.acknowledge-mode")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.acknowledge-mode")
@Deprecated
public AcknowledgeMode getAcknowledgeMode() {
return getSimple().getAcknowledgeMode();
@@ -521,8 +519,7 @@ public class RabbitProperties {
getSimple().setAcknowledgeMode(acknowledgeMode);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.concurrency")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.concurrency")
@Deprecated
public Integer getConcurrency() {
return getSimple().getConcurrency();
@@ -533,8 +530,7 @@ public class RabbitProperties {
getSimple().setConcurrency(concurrency);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.max-concurrency")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.max-concurrency")
@Deprecated
public Integer getMaxConcurrency() {
return getSimple().getMaxConcurrency();
@@ -545,8 +541,7 @@ public class RabbitProperties {
getSimple().setMaxConcurrency(maxConcurrency);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.prefetch")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.prefetch")
@Deprecated
public Integer getPrefetch() {
return getSimple().getPrefetch();
@@ -557,8 +552,7 @@ public class RabbitProperties {
getSimple().setPrefetch(prefetch);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.transaction-size")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.transaction-size")
@Deprecated
public Integer getTransactionSize() {
return getSimple().getTransactionSize();
@@ -569,8 +563,7 @@ public class RabbitProperties {
getSimple().setTransactionSize(transactionSize);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.default-requeue-rejected")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.default-requeue-rejected")
@Deprecated
public Boolean getDefaultRequeueRejected() {
return getSimple().getDefaultRequeueRejected();
@@ -581,8 +574,7 @@ public class RabbitProperties {
getSimple().setDefaultRequeueRejected(defaultRequeueRejected);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.idle-event-interval")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.idle-event-interval")
@Deprecated
public Long getIdleEventInterval() {
return getSimple().getIdleEventInterval();
@@ -593,8 +585,7 @@ public class RabbitProperties {
getSimple().setIdleEventInterval(idleEventInterval);
}
@DeprecatedConfigurationProperty(
replacement = "spring.rabbitmq.listener.simple.retry")
@DeprecatedConfigurationProperty(replacement = "spring.rabbitmq.listener.simple.retry")
@Deprecated
public ListenerRetry getRetry() {
return getSimple().getRetry();

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,16 +73,14 @@ public final class SimpleRabbitListenerContainerFactoryConfigurer {
* configure
* @param connectionFactory the {@link ConnectionFactory} to use
*/
public void configure(SimpleRabbitListenerContainerFactory factory,
ConnectionFactory connectionFactory) {
public void configure(SimpleRabbitListenerContainerFactory factory, ConnectionFactory connectionFactory) {
Assert.notNull(factory, "Factory must not be null");
Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
factory.setConnectionFactory(connectionFactory);
if (this.messageConverter != null) {
factory.setMessageConverter(this.messageConverter);
}
RabbitProperties.AmqpContainer config = this.rabbitProperties.getListener()
.getSimple();
RabbitProperties.AmqpContainer config = this.rabbitProperties.getListener().getSimple();
factory.setAutoStartup(config.isAutoStartup());
if (config.getAcknowledgeMode() != null) {
factory.setAcknowledgeMode(config.getAcknowledgeMode());
@@ -107,14 +105,13 @@ public final class SimpleRabbitListenerContainerFactoryConfigurer {
}
ListenerRetry retryConfig = config.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(),
retryConfig.getMultiplier(), retryConfig.getMaxInterval());
MessageRecoverer recoverer = (this.messageRecoverer != null)
? this.messageRecoverer : new RejectAndDontRequeueRecoverer();
builder.backOffOptions(retryConfig.getInitialInterval(), retryConfig.getMultiplier(),
retryConfig.getMaxInterval());
MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer
: new RejectAndDontRequeueRecoverer();
builder.recoverer(recoverer);
factory.setAdviceChain(builder.build());
}

View File

@@ -40,22 +40,21 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy;
*/
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true",
matchIfMissing = true)
@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 = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
matchIfMissing = true)
public static class JdkDynamicAutoProxyConfiguration {
}
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class",
havingValue = "true", matchIfMissing = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
matchIfMissing = false)
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.
@@ -84,8 +84,7 @@ public class BasicBatchConfigurer implements BatchConfigurer {
* {@code null})
*/
protected BasicBatchConfigurer(BatchProperties properties, DataSource dataSource,
EntityManagerFactory entityManagerFactory,
TransactionManagerCustomizers transactionManagerCustomizers) {
EntityManagerFactory entityManagerFactory, TransactionManagerCustomizers transactionManagerCustomizers) {
this.properties = properties;
this.entityManagerFactory = entityManagerFactory;
this.dataSource = dataSource;
@@ -147,8 +146,7 @@ public class BasicBatchConfigurer implements BatchConfigurer {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(this.dataSource);
if (this.entityManagerFactory != null) {
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");
factory.setIsolationLevelForCreate("ISOLATION_DEFAULT");
}
String tablePrefix = this.properties.getTablePrefix();

View File

@@ -81,19 +81,15 @@ public class BatchAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(DataSource.class)
public BatchDatabaseInitializer batchDatabaseInitializer(DataSource dataSource,
ResourceLoader resourceLoader) {
public BatchDatabaseInitializer batchDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
return new BatchDatabaseInitializer(dataSource, resourceLoader, this.properties);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled",
havingValue = "true", matchIfMissing = true)
public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(
JobLauncher jobLauncher, JobExplorer jobExplorer) {
JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(
jobLauncher, jobExplorer);
@ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true)
public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) {
JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(jobLauncher, jobExplorer);
String jobNames = this.properties.getJob().getNames();
if (StringUtils.hasText(jobNames)) {
runner.setJobNames(jobNames);
@@ -124,8 +120,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);
@@ -138,8 +133,7 @@ public class BatchAutoConfiguration {
}
@EnableConfigurationProperties(BatchProperties.class)
@ConditionalOnClass(value = PlatformTransactionManager.class,
name = "javax.persistence.EntityManagerFactory")
@ConditionalOnClass(value = PlatformTransactionManager.class, name = "javax.persistence.EntityManagerFactory")
@ConditionalOnMissingBean(BatchConfigurer.class)
@Configuration
protected static class JpaBatchConfiguration {
@@ -155,11 +149,10 @@ public class BatchAutoConfiguration {
// Boot in the JPA auto configuration.
@Bean
@ConditionalOnBean(name = "entityManagerFactory")
public BasicBatchConfigurer jpaBatchConfigurer(DataSource dataSource,
EntityManagerFactory entityManagerFactory,
public BasicBatchConfigurer jpaBatchConfigurer(DataSource dataSource, EntityManagerFactory entityManagerFactory,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
return new BasicBatchConfigurer(this.properties, dataSource,
entityManagerFactory, transactionManagerCustomizers.getIfAvailable());
return new BasicBatchConfigurer(this.properties, dataSource, entityManagerFactory,
transactionManagerCustomizers.getIfAvailable());
}
@Bean

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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 @@ public class BatchDatabaseInitializer extends AbstractDatabaseInitializer {
private final BatchProperties properties;
public BatchDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader,
BatchProperties properties) {
public BatchDatabaseInitializer(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.
@@ -83,8 +83,7 @@ public class BatchProperties {
return this.enabled;
}
boolean defaultTablePrefix = BatchProperties.this.getTablePrefix() == null;
boolean customSchema = !DEFAULT_SCHEMA_LOCATION
.equals(BatchProperties.this.getSchema());
boolean customSchema = !DEFAULT_SCHEMA_LOCATION.equals(BatchProperties.this.getSchema());
return (defaultTablePrefix || customSchema);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 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<JobExecution>();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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.
@@ -61,11 +61,9 @@ import org.springframework.util.StringUtils;
* @author Dave Syer
* @author Jean-Pierre Bergamin
*/
public class JobLauncherCommandLineRunner
implements CommandLineRunner, ApplicationEventPublisherAware {
public class JobLauncherCommandLineRunner implements CommandLineRunner, ApplicationEventPublisherAware {
private static final Log logger = LogFactory
.getLog(JobLauncherCommandLineRunner.class);
private static final Log logger = LogFactory.getLog(JobLauncherCommandLineRunner.class);
private JobParametersConverter converter = new DefaultJobParametersConverter();
@@ -81,8 +79,7 @@ public class JobLauncherCommandLineRunner
private ApplicationEventPublisher publisher;
public JobLauncherCommandLineRunner(JobLauncher jobLauncher,
JobExplorer jobExplorer) {
public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) {
this.jobLauncher = jobLauncher;
this.jobExplorer = jobExplorer;
}
@@ -117,15 +114,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 JobParameters getNextJobParameters(Job job,
JobParameters additionalParameters) {
private JobParameters getNextJobParameters(Job job, JobParameters additionalParameters) {
String name = job.getName();
JobParameters parameters = new JobParameters();
List<JobInstance> lastInstances = this.jobExplorer.getJobInstances(name, 0, 1);
@@ -138,8 +133,7 @@ public class JobLauncherCommandLineRunner
}
}
else {
List<JobExecution> previousExecutions = this.jobExplorer
.getJobExecutions(lastInstances.get(0));
List<JobExecution> previousExecutions = this.jobExplorer.getJobExecutions(lastInstances.get(0));
JobExecution previousExecution = previousExecutions.get(0);
if (previousExecution == null) {
// Normally this will not happen - an instance exists with no executions
@@ -167,8 +161,7 @@ public class JobLauncherCommandLineRunner
}
private void removeNonIdentifying(Map<String, JobParameter> parameters) {
HashMap<String, JobParameter> copy = new HashMap<String, JobParameter>(
parameters);
HashMap<String, JobParameter> copy = new HashMap<String, JobParameter>(parameters);
for (Map.Entry<String, JobParameter> parameter : copy.entrySet()) {
if (!parameter.getValue().isIdentifying()) {
parameters.remove(parameter.getKey());
@@ -176,16 +169,14 @@ public class JobLauncherCommandLineRunner
}
}
private JobParameters merge(JobParameters parameters,
Map<String, JobParameter> additionals) {
private JobParameters merge(JobParameters parameters, Map<String, JobParameter> additionals) {
Map<String, JobParameter> merged = new HashMap<String, JobParameter>();
merged.putAll(parameters.getParameters());
merged.putAll(additionals);
return new JobParameters(merged);
}
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) {
@@ -204,9 +195,8 @@ public class JobLauncherCommandLineRunner
}
protected void execute(Job job, JobParameters jobParameters)
throws JobExecutionAlreadyRunningException, JobRestartException,
JobInstanceAlreadyCompleteException, JobParametersInvalidException,
JobParametersNotFoundException {
throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException, JobParametersNotFoundException {
JobParameters nextParameters = getNextJobParameters(job, jobParameters);
JobExecution execution = this.jobLauncher.run(job, nextParameters);
if (this.publisher != null) {
@@ -214,8 +204,7 @@ public class JobLauncherCommandLineRunner
}
}
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(",");

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.
@@ -74,16 +74,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");
@@ -101,8 +100,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;
}
@@ -110,9 +108,8 @@ public class CacheAutoConfiguration {
@Override
public void afterPropertiesSet() {
Assert.notNull(this.cacheManager.getIfAvailable(),
"No cache manager could "
+ "be auto-configured, check your configuration (caching "
+ "type is '" + this.cacheProperties.getType() + "')");
"No cache manager could " + "be auto-configured, check your configuration (caching " + "type is '"
+ this.cacheProperties.getType() + "')");
}
}

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,23 +37,18 @@ 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);
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), "spring.cache.");
ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", sourceClass);
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "spring.cache.");
if (!resolver.containsProperty("type")) {
return ConditionOutcome.match(message.because("automatic cache type"));
}
CacheType cacheType = CacheConfigurations
.getType(((AnnotationMetadata) metadata).getClassName());
String value = resolver.getProperty("type").replace('-', '_')
.toUpperCase(Locale.ENGLISH);
CacheType cacheType = CacheConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
String value = resolver.getProperty("type").replace('-', '_').toUpperCase(Locale.ENGLISH);
if (value.equals(cacheType.name())) {
return ConditionOutcome.match(message.because(value + " cache type"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,8 +68,7 @@ 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.
@@ -39,10 +39,8 @@ public class CacheManagerCustomizers {
private final List<CacheManagerCustomizer<?>> customizers;
public CacheManagerCustomizers(
List<? extends CacheManagerCustomizer<?>> customizers) {
this.customizers = (customizers != null)
? new ArrayList<CacheManagerCustomizer<?>>(customizers)
public CacheManagerCustomizers(List<? extends CacheManagerCustomizer<?>> customizers) {
this.customizers = (customizers != null) ? new ArrayList<CacheManagerCustomizer<?>>(customizers)
: Collections.<CacheManagerCustomizer<?>>emptyList();
}
@@ -56,8 +54,7 @@ public class CacheManagerCustomizers {
*/
public <T extends CacheManager> T customize(T cacheManager) {
for (CacheManagerCustomizer<?> customizer : this.customizers) {
Class<?> generic = ResolvableType
.forClass(CacheManagerCustomizer.class, customizer.getClass())
Class<?> generic = ResolvableType.forClass(CacheManagerCustomizer.class, customizer.getClass())
.resolveGeneric();
if (generic.isInstance(cacheManager)) {
customize(cacheManager, customizer);
@@ -75,9 +72,7 @@ public class CacheManagerCustomizers {
// Possibly a lambda-defined customizer which we could not resolve the generic
// cache manager type for
if (logger.isDebugEnabled()) {
logger.debug(
"Non-matching cache manager type for customizer: " + customizer,
ex);
logger.debug("Non-matching cache manager type for customizer: " + customizer, ex);
}
}
}

View File

@@ -114,8 +114,7 @@ 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;
@@ -283,8 +282,7 @@ public class CacheProperties {
private String spec;
@Deprecated
@DeprecatedConfigurationProperty(
reason = "Caffeine will supersede the Guava support in Spring Boot 2.0",
@DeprecatedConfigurationProperty(reason = "Caffeine will supersede the Guava support in Spring Boot 2.0",
replacement = "spring.cache.caffeine.spec")
public String getSpec() {
return this.spec;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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.
@@ -49,8 +49,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;
@@ -60,8 +60,8 @@ public class CouchbaseCacheConfiguration {
public CouchbaseCacheManager cacheManager() {
List<String> cacheNames = this.cacheProperties.getCacheNames();
CouchbaseCacheManager cacheManager = new CouchbaseCacheManager(
CacheBuilder.newInstance(this.bucket).withExpiration(
this.cacheProperties.getCouchbase().getExpirationSeconds()),
CacheBuilder.newInstance(this.bucket)
.withExpiration(this.cacheProperties.getCouchbase().getExpirationSeconds()),
cacheNames.toArray(new String[cacheNames.size()]));
return this.customizers.customize(cacheManager);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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,16 +40,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;
}
@@ -62,8 +60,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-2016 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.
@@ -56,8 +56,7 @@ class GuavaCacheConfiguration {
private final CacheLoader<Object, Object> cacheLoader;
GuavaCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizers,
GuavaCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers,
ObjectProvider<CacheBuilder<Object, Object>> cacheBuilder,
ObjectProvider<CacheBuilderSpec> cacheBuilderSpec,
ObjectProvider<CacheLoader<Object, Object>> cacheLoader) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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.context.annotation.Import;
@ConditionalOnClass({ HazelcastInstance.class, HazelcastCacheManager.class })
@ConditionalOnMissingBean(CacheManager.class)
@Conditional(CacheCondition.class)
@Import({ HazelcastInstanceConfiguration.Existing.class,
HazelcastInstanceConfiguration.Specific.class })
@Import({ HazelcastInstanceConfiguration.Existing.class, HazelcastInstanceConfiguration.Specific.class })
class HazelcastCacheConfiguration {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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,18 +54,16 @@ abstract class HazelcastInstanceConfiguration {
}
@Bean
public HazelcastCacheManager cacheManager(
HazelcastInstance existingHazelcastInstance) throws IOException {
public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance) throws IOException {
@SuppressWarnings("deprecation")
Resource config = this.cacheProperties.getHazelcast().getConfig();
Resource location = this.cacheProperties.resolveConfigLocation(config);
if (location != null) {
HazelcastInstance cacheHazelcastInstance = new HazelcastInstanceFactory(
location).getHazelcastInstance();
HazelcastInstance cacheHazelcastInstance = new HazelcastInstanceFactory(location)
.getHazelcastInstance();
return new CloseableHazelcastCacheManager(cacheHazelcastInstance);
}
HazelcastCacheManager cacheManager = new HazelcastCacheManager(
existingHazelcastInstance);
HazelcastCacheManager cacheManager = new HazelcastCacheManager(existingHazelcastInstance);
return this.customizers.customize(cacheManager);
}
@@ -98,8 +96,7 @@ abstract class HazelcastInstanceConfiguration {
@Bean
public HazelcastCacheManager cacheManager() throws IOException {
HazelcastCacheManager cacheManager = new HazelcastCacheManager(
hazelcastInstance());
HazelcastCacheManager cacheManager = new HazelcastCacheManager(hazelcastInstance());
return this.customizers.customize(cacheManager);
}
@@ -117,8 +114,7 @@ abstract class HazelcastInstanceConfiguration {
}
private static class CloseableHazelcastCacheManager extends HazelcastCacheManager
implements Closeable {
private static class CloseableHazelcastCacheManager extends HazelcastCacheManager implements Closeable {
private final HazelcastInstance hazelcastInstance;

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-2016 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 @@ 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;
@@ -63,10 +62,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,7 @@ public class InfinispanCacheConfiguration {
List<String> cacheNames = this.cacheProperties.getCacheNames();
if (!CollectionUtils.isEmpty(cacheNames)) {
for (String cacheName : cacheNames) {
cacheManager.defineConfiguration(cacheName,
getDefaultCacheConfiguration());
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,29 +188,23 @@ 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");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), "spring.cache.jcache.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(),
"spring.cache.jcache.");
if (resolver.containsProperty("provider")) {
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-2016 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,8 +46,7 @@ class RedisCacheConfiguration {
private final CacheManagerCustomizers customizerInvoker;
RedisCacheConfiguration(CacheProperties cacheProperties,
CacheManagerCustomizers customizerInvoker) {
RedisCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker) {
this.cacheProperties = cacheProperties;
this.customizerInvoker = customizerInvoker;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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-2016 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.
@@ -63,8 +63,7 @@ public class CassandraAutoConfiguration {
@ConditionalOnMissingBean
public Cluster cluster() {
CassandraProperties properties = this.properties;
Cluster.Builder builder = Cluster.builder()
.withClusterName(properties.getClusterName())
Cluster.Builder builder = Cluster.builder().withClusterName(properties.getClusterName())
.withPort(properties.getPort());
if (properties.getUsername() != null) {
builder.withCredentials(properties.getUsername(), properties.getPassword());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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.
@@ -183,8 +183,7 @@ public class CassandraProperties {
return this.loadBalancingPolicy;
}
public void setLoadBalancingPolicy(
Class<? extends LoadBalancingPolicy> loadBalancingPolicy) {
public void setLoadBalancingPolicy(Class<? extends LoadBalancingPolicy> loadBalancingPolicy) {
this.loadBalancingPolicy = loadBalancingPolicy;
}
@@ -216,8 +215,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.
@@ -41,8 +41,7 @@ import org.springframework.util.MultiValueMap;
*
* @author Phillip Webb
*/
abstract class AbstractNestedCondition extends SpringBootCondition
implements ConfigurationCondition {
abstract class AbstractNestedCondition extends SpringBootCondition implements ConfigurationCondition {
private final ConfigurationPhase configurationPhase;
@@ -57,16 +56,14 @@ 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 {
@@ -111,14 +108,12 @@ 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<AnnotationMetadata, Condition>();
for (String member : members) {
AnnotationMetadata metadata = getMetadata(member);
@@ -134,8 +129,7 @@ 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);
@@ -144,26 +138,23 @@ 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<ConditionOutcome>();
for (Map.Entry<AnnotationMetadata, List<Condition>> entry : this.memberConditions
.entrySet()) {
for (Map.Entry<AnnotationMetadata, List<Condition>> entry : this.memberConditions.entrySet()) {
AnnotationMetadata metadata = entry.getKey();
List<Condition> conditions = entry.getValue();
outcomes.add(new MemberOutcomes(this.context, metadata, conditions)
.getUltimateOutcome());
outcomes.add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome());
}
return Collections.unmodifiableList(outcomes);
}
@@ -178,8 +169,7 @@ 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<ConditionOutcome>(conditions.size());
@@ -188,24 +178,19 @@ 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<ConditionOutcome>();
List<ConditionOutcome> nonMatch = new ArrayList<ConditionOutcome>();
@@ -213,11 +198,9 @@ 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<ConditionMessage>();
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<ConditionMessage>();
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);
@@ -134,8 +133,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
updateTypesIfNecessary();
Set<String> matches = new LinkedHashSet<String>();
for (Map.Entry<String, Class<?>> entry : this.beanTypes.entrySet()) {
if (entry.getValue() != null && AnnotationUtils
.findAnnotation(entry.getValue(), annotation) != null) {
if (entry.getValue() != null && AnnotationUtils.findAnnotation(entry.getValue(), annotation) != null) {
matches.add(entry.getKey());
}
}
@@ -213,18 +211,14 @@ final class BeanTypeRegistry implements SmartInitializingSingleton {
}
}
private void addBeanTypeForNonAliasDefinition(String name,
RootBeanDefinition beanDefinition) {
private void addBeanTypeForNonAliasDefinition(String name, RootBeanDefinition beanDefinition) {
try {
String factoryName = BeanFactory.FACTORY_BEAN_PREFIX + name;
if (!beanDefinition.isAbstract()
&& !requiresEagerInit(beanDefinition.getFactoryBeanName())) {
if (!beanDefinition.isAbstract() && !requiresEagerInit(beanDefinition.getFactoryBeanName())) {
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));
@@ -245,8 +239,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);
}
@@ -255,8 +248,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())) {
@@ -268,32 +260,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);
@@ -314,10 +299,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());
}
@@ -330,23 +313,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-2016 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.
@@ -74,8 +74,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");
@@ -112,8 +111,7 @@ public final class ConditionEvaluationReport {
*/
public Map<String, ConditionAndOutcomes> getConditionAndOutcomesBySource() {
if (!this.addedAncestorOutcomes) {
for (Map.Entry<String, ConditionAndOutcomes> entry : this.outcomes
.entrySet()) {
for (Map.Entry<String, ConditionAndOutcomes> entry : this.outcomes.entrySet()) {
if (!entry.getValue().isFullMatch()) {
addNoMatchOutcomeToAncestors(entry.getKey());
}
@@ -127,8 +125,8 @@ public final class ConditionEvaluationReport {
String prefix = source + "$";
for (Entry<String, ConditionAndOutcomes> entry : this.outcomes.entrySet()) {
if (entry.getKey().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"));
entry.getValue().add(ANCESTOR_CONDITION, outcome);
}
}
@@ -163,8 +161,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)) {
@@ -179,12 +176,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);
}
}
@@ -250,8 +244,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;
@@ -358,8 +355,7 @@ public final class ConditionMessage {
* @return a built {@link ConditionMessage}
*/
public ConditionMessage items(Style style, Object... items) {
return items(style,
(items != null) ? Arrays.asList(items) : (Collection<?>) null);
return items(style, (items != null) ? Arrays.asList(items) : (Collection<?>) null);
}
/**
@@ -385,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 ObjectUtils.hashCode(this.match) * 31
+ ObjectUtils.nullSafeHashCode(this.message);
return ObjectUtils.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<ConditionMessage>();
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.
@@ -70,65 +70,53 @@ 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);
List<String> matching = getMatchingBeans(context, spec);
if (matching.isEmpty()) {
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(ConditionalOnBean.class, spec)
.didNotFind("any beans").atAll());
ConditionMessage.forCondition(ConditionalOnBean.class, spec).didNotFind("any beans").atAll());
}
matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec)
.found("bean", "beans").items(Style.QUOTE, matching);
matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec).found("bean", "beans")
.items(Style.QUOTE, matching);
}
if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
BeanSearchSpec spec = new SingleCandidateBeanSearchSpec(context, metadata,
ConditionalOnSingleCandidate.class);
List<String> matching = getMatchingBeans(context, spec);
if (matching.isEmpty()) {
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(), matching,
spec.getStrategy() == SearchStrategy.ALL)) {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnSingleCandidate.class, spec)
.didNotFind("a primary bean from beans")
.items(Style.QUOTE, matching));
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSingleCandidate.class, spec)
.didNotFind("a primary bean from beans").items(Style.QUOTE, matching));
}
matchMessage = matchMessage
.andCondition(ConditionalOnSingleCandidate.class, spec)
matchMessage = matchMessage.andCondition(ConditionalOnSingleCandidate.class, spec)
.found("a primary bean from beans").items(Style.QUOTE, matching);
}
if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
ConditionalOnMissingBean.class);
BeanSearchSpec spec = new BeanSearchSpec(context, metadata, ConditionalOnMissingBean.class);
List<String> matching = getMatchingBeans(context, spec);
if (!matching.isEmpty()) {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnMissingBean.class, spec)
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingBean.class, spec)
.found("bean", "beans").items(Style.QUOTE, matching));
}
matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec)
.didNotFind("any beans").atAll();
matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec).didNotFind("any beans")
.atAll();
}
return ConditionOutcome.match(matchMessage);
}
@SuppressWarnings("deprecation")
private List<String> getMatchingBeans(ConditionContext context,
BeanSearchSpec beans) {
private List<String> getMatchingBeans(ConditionContext context, BeanSearchSpec beans) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
if (beans.getStrategy() == SearchStrategy.PARENTS
|| beans.getStrategy() == SearchStrategy.ANCESTORS) {
if (beans.getStrategy() == SearchStrategy.PARENTS || 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;
}
if (beanFactory == null) {
@@ -137,16 +125,15 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
List<String> beanNames = new ArrayList<String>();
boolean considerHierarchy = beans.getStrategy() != SearchStrategy.CURRENT;
for (String type : beans.getTypes()) {
beanNames.addAll(getBeanNamesForType(beanFactory, type,
context.getClassLoader(), considerHierarchy));
beanNames.addAll(getBeanNamesForType(beanFactory, type, context.getClassLoader(), considerHierarchy));
}
for (String ignoredType : beans.getIgnoredTypes()) {
beanNames.removeAll(getBeanNamesForType(beanFactory, ignoredType,
context.getClassLoader(), considerHierarchy));
beanNames.removeAll(
getBeanNamesForType(beanFactory, ignoredType, context.getClassLoader(), considerHierarchy));
}
for (String annotation : beans.getAnnotations()) {
beanNames.addAll(Arrays.asList(getBeanNamesForAnnotation(beanFactory,
annotation, context.getClassLoader(), considerHierarchy)));
beanNames.addAll(Arrays.asList(
getBeanNamesForAnnotation(beanFactory, annotation, context.getClassLoader(), considerHierarchy)));
}
for (String beanName : beans.getNames()) {
if (containsBean(beanFactory, beanName, considerHierarchy)) {
@@ -156,21 +143,19 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit
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<String>();
collectBeanNamesForType(result, beanFactory,
ClassUtils.forName(type, classLoader), considerHierarchy);
collectBeanNamesForType(result, beanFactory, ClassUtils.forName(type, classLoader), considerHierarchy);
return result;
}
catch (ClassNotFoundException ex) {
@@ -181,29 +166,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<String>();
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
@@ -211,35 +192,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, List<String> beanNames,
private boolean hasSingleAutowireCandidate(ConfigurableListableBeanFactory beanFactory, List<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,
List<String> beanNames, boolean considerHierarchy) {
private List<String> getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, List<String> beanNames,
boolean considerHierarchy) {
List<String> primaryBeans = new ArrayList<String>();
for (String beanName : beanNames) {
BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName,
considerHierarchy);
BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, considerHierarchy);
if (beanDefinition != null && beanDefinition.isPrimary()) {
primaryBeans.add(beanName);
}
@@ -247,15 +220,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;
@@ -275,19 +247,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()) {
@@ -302,13 +272,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);
}
}
@@ -325,8 +293,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) {
@@ -340,27 +307,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);
}
}
@@ -409,32 +372,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);
}
}

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,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);
List<String> candidates = new ArrayList<String>();
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<String>(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);
}
@@ -257,8 +239,7 @@ class OnClassCondition extends SpringBootCondition
@Override
public void run() {
ThreadedOutcomesResolver.this.outcomes = outcomesResolver
.resolveOutcomes();
ThreadedOutcomesResolver.this.outcomes = outcomesResolver.resolveOutcomes();
}
});
@@ -290,9 +271,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;
@@ -302,17 +282,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(final String[] autoConfigurationClasses,
int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) {
private ConditionOutcome[] getOutcomes(final 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);
}
@@ -322,13 +300,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-2016 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,35 +36,30 @@ 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);
String rawExpression = expression;
expression = context.getEnvironment().resolvePlaceholders(expression);
ConditionMessage.Builder messageBuilder = ConditionMessage
.forCondition(ConditionalOnExpression.class, "(" + rawExpression + ")");
ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class,
"(" + rawExpression + ")");
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
if (beanFactory != null) {
boolean result = evaluateExpression(beanFactory, expression);
return new ConditionOutcome(result, messageBuilder.resultedIn(result));
}
else {
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);
return (Boolean) resolver.evaluate(expression, expressionContext);
}

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 = runningVersion.isWithin(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);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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.
@@ -49,16 +49,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<ConditionMessage>();
List<ConditionMessage> match = new ArrayList<ConditionMessage>();
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()) {
@@ -83,35 +80,29 @@ class OnPropertyCondition extends SpringBootCondition {
map.put(entry.getKey(), entry.getValue().get(i));
}
}
List<AnnotationAttributes> annotationAttributes = new ArrayList<AnnotationAttributes>(
maps.size());
List<AnnotationAttributes> annotationAttributes = new ArrayList<AnnotationAttributes>(maps.size());
for (Map<String, Object> map : maps) {
annotationAttributes.add(AnnotationAttributes.fromMap(map));
}
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<String>();
List<String> nonMatchingProperties = new ArrayList<String>();
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 {
@@ -148,8 +139,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) {
if (this.relaxedNames) {
resolver = new RelaxedPropertyResolver(resolver, this.prefix);
}

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<String>();
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<String>();
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-2016 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,10 +41,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());
@@ -55,13 +53,12 @@ class OnWebApplicationCondition extends SpringBootCondition {
return ConditionOutcome.match(outcome.getConditionMessage());
}
private ConditionOutcome isWebApplication(ConditionContext context,
AnnotatedTypeMetadata metadata, boolean required) {
ConditionMessage.Builder message = ConditionMessage.forCondition(
ConditionalOnWebApplication.class, required ? "(required)" : "");
private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata,
boolean required) {
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnWebApplication.class,
required ? "(required)" : "");
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();
@@ -70,8 +67,7 @@ class OnWebApplicationCondition extends SpringBootCondition {
}
}
if (context.getEnvironment() instanceof StandardServletEnvironment) {
return ConditionOutcome
.match(message.foundExactly("StandardServletEnvironment"));
return ConditionOutcome.match(message.foundExactly("StandardServletEnvironment"));
}
if (context.getResourceLoader() instanceof WebApplicationContext) {
return ConditionOutcome.match(message.foundExactly("WebApplicationContext"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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,7 @@ public abstract class ResourceCondition extends SpringBootCondition {
* @param resourceLocations default location(s) where the configuration file can be
* found if the configuration key is not specified
*/
protected ResourceCondition(String name, String prefix, String propertyName,
String... resourceLocations) {
protected ResourceCondition(String name, String prefix, String propertyName, String... resourceLocations) {
this.name = name;
this.prefix = (prefix.endsWith(".") ? prefix : prefix + ".");
this.propertyName = propertyName;
@@ -62,13 +61,11 @@ public abstract class ResourceCondition extends SpringBootCondition {
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), this.prefix);
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), this.prefix);
if (resolver.containsProperty(this.propertyName)) {
return ConditionOutcome.match(startConditionMessage()
.foundExactly("property " + this.prefix + this.propertyName));
return ConditionOutcome
.match(startConditionMessage().foundExactly("property " + this.prefix + this.propertyName));
}
return getResourceOutcome(context, metadata);
}
@@ -79,8 +76,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<String>();
for (String location : this.resourceLocations) {
Resource resource = context.getResourceLoader().getResource(location);
@@ -89,13 +85,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.
@@ -94,8 +94,8 @@ public class MessageSourceAutoConfiguration {
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename)));
messageSource.setBasenames(
StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(this.basename)));
}
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name());
@@ -151,10 +151,8 @@ public class MessageSourceAutoConfiguration {
private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<String, ConditionOutcome>();
@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);
@@ -163,21 +161,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

@@ -68,8 +68,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
@@ -77,8 +76,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();
}
@@ -94,18 +92,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().connectTimeout(timeouts.getConnect())
.kvEndpoints(endpoints.getKeyValue())
.kvTimeout(timeouts.getKeyValue())
.queryEndpoints(endpoints.getQuery())
DefaultCouchbaseEnvironment.Builder builder = DefaultCouchbaseEnvironment.builder()
.connectTimeout(timeouts.getConnect()).kvEndpoints(endpoints.getKeyValue())
.kvTimeout(timeouts.getKeyValue()).queryEndpoints(endpoints.getQuery())
.queryTimeout(timeouts.getQuery()).viewEndpoints(endpoints.getView())
.socketConnectTimeout(timeouts.getSocketConnect())
.viewTimeout(timeouts.getView());
.socketConnectTimeout(timeouts.getSocketConnect()).viewTimeout(timeouts.getView());
CouchbaseProperties.Ssl ssl = properties.getEnv().getSsl();
if (ssl.getEnabled()) {
builder.sslEnabled(true);
@@ -140,8 +134,7 @@ public class CouchbaseAutoConfiguration {
}
@ConditionalOnBean(
type = "org.springframework.data.couchbase.config.CouchbaseConfigurer")
@ConditionalOnBean(type = "org.springframework.data.couchbase.config.CouchbaseConfigurer")
static class CouchbaseConfigurerAvailable {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -174,8 +174,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-2016 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,20 +41,16 @@ import org.springframework.validation.DataBinder;
class OnBootstrapHostsCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
PropertyResolver resolver = new PropertyResolver(
((ConfigurableEnvironment) environment).getPropertySources(),
PropertyResolver resolver = new PropertyResolver(((ConfigurableEnvironment) environment).getPropertySources(),
"spring.couchbase");
Map.Entry<String, Object> entry = resolver.resolveProperty("bootstrap-hosts");
if (entry != null) {
return ConditionOutcome.match(ConditionMessage
.forCondition(OnBootstrapHostsCondition.class.getName())
return ConditionOutcome.match(ConditionMessage.forCondition(OnBootstrapHostsCondition.class.getName())
.found("property").items("spring.couchbase.bootstrap-hosts"));
}
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(OnBootstrapHostsCondition.class.getName())
return ConditionOutcome.noMatch(ConditionMessage.forCondition(OnBootstrapHostsCondition.class.getName())
.didNotFind("property").items("spring.couchbase.bootstrap-hosts"));
}
@@ -78,8 +74,7 @@ class OnBootstrapHostsCondition extends SpringBootCondition {
for (String relaxedKey : keys) {
String key = prefix + relaxedKey;
if (this.content.containsKey(relaxedKey)) {
return new AbstractMap.SimpleEntry<String, Object>(key,
this.content.get(relaxedKey));
return new AbstractMap.SimpleEntry<String, Object>(key, this.content.get(relaxedKey));
}
}
}

View File

@@ -40,8 +40,7 @@ public class PersistenceExceptionTranslationAutoConfiguration {
@Bean
@ConditionalOnMissingBean(PersistenceExceptionTranslationPostProcessor.class)
@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();
@@ -50,8 +49,7 @@ public class PersistenceExceptionTranslationAutoConfiguration {
}
private static boolean determineProxyTargetClass(Environment environment) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment,
"spring.aop.");
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "spring.aop.");
Boolean value = resolver.getProperty("proxyTargetClass", Boolean.class);
return (value != null) ? value : true;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 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 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Oliver Gierke
*/
public abstract class AbstractRepositoryConfigurationSourceSupport
implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware,
EnvironmentAware {
implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
private ResourceLoader resourceLoader;
@@ -53,23 +52,18 @@ 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 registry) {
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(
getConfiguration(), true);
return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(),
this.resourceLoader, this.environment, registry) {
private AnnotationRepositoryConfigurationSource getConfigurationSource(BeanDefinitionRegistry registry) {
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getConfiguration(), true);
return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader,
this.environment, registry) {
@Override
public java.lang.Iterable<String> getBasePackages() {
return AbstractRepositoryConfigurationSourceSupport.this
.getBasePackages();
return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages();
}
};
}

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.
@@ -71,21 +71,19 @@ public class CassandraDataAutoConfiguration {
private final PropertyResolver propertyResolver;
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;
this.propertyResolver = new RelaxedPropertyResolver(environment,
"spring.data.cassandra.");
this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.data.cassandra.");
}
@Bean
@ConditionalOnMissingBean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
BasicCassandraMappingContext context = new BasicCassandraMappingContext();
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);
}
@@ -93,8 +91,7 @@ public class CassandraDataAutoConfiguration {
context.setInitialEntitySet(CassandraEntityClassScanner.scan(packages));
}
if (StringUtils.hasText(this.properties.getKeyspaceName())) {
context.setUserTypeResolver(new SimpleUserTypeResolver(this.cluster,
this.properties.getKeyspaceName()));
context.setUserTypeResolver(new SimpleUserTypeResolver(this.cluster, this.properties.getKeyspaceName()));
}
return context;
}
@@ -107,24 +104,20 @@ public class CassandraDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean(Session.class)
public CassandraSessionFactoryBean session(CassandraConverter converter)
throws Exception {
public CassandraSessionFactoryBean session(CassandraConverter converter) throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(this.cluster);
session.setConverter(converter);
session.setKeyspaceName(this.properties.getKeyspaceName());
String name = this.propertyResolver.getProperty("schemaAction",
SchemaAction.NONE.name());
SchemaAction schemaAction = SchemaAction
.valueOf(name.toUpperCase(Locale.ENGLISH));
String name = this.propertyResolver.getProperty("schemaAction", SchemaAction.NONE.name());
SchemaAction schemaAction = SchemaAction.valueOf(name.toUpperCase(Locale.ENGLISH));
session.setSchemaAction(schemaAction);
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

@@ -38,8 +38,8 @@ import org.springframework.data.cassandra.repository.support.CassandraRepository
*/
@Configuration
@ConditionalOnClass({ Session.class, CassandraRepository.class })
@ConditionalOnProperty(prefix = "spring.data.cassandra.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.cassandra.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnMissingBean(CassandraRepositoryFactoryBean.class)
@Import(CassandraRepositoriesAutoConfigureRegistrar.class)
public class CassandraRepositoriesAutoConfiguration {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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-2016 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-2016 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

@@ -40,8 +40,8 @@ import org.springframework.data.couchbase.repository.support.CouchbaseRepository
@Configuration
@ConditionalOnClass({ Bucket.class, CouchbaseRepository.class })
@ConditionalOnBean(RepositoryOperationsMapping.class)
@ConditionalOnProperty(prefix = "spring.data.couchbase.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.couchbase.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnMissingBean(CouchbaseRepositoryFactoryBean.class)
@Import(CouchbaseRepositoriesRegistrar.class)
public class CouchbaseRepositoriesAutoConfiguration {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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-2016 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-2016 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-2016 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 @@ import org.springframework.util.StringUtils;
* @since 1.1.0
*/
@Configuration
@ConditionalOnClass({ Client.class, TransportClientFactoryBean.class,
NodeClientFactoryBean.class })
@ConditionalOnClass({ Client.class, TransportClientFactoryBean.class, NodeClientFactoryBean.class })
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchAutoConfiguration implements DisposableBean {
@@ -66,8 +65,7 @@ public class ElasticsearchAutoConfiguration implements DisposableBean {
DEFAULTS = Collections.unmodifiableMap(defaults);
}
private static final Log logger = LogFactory
.getLog(ElasticsearchAutoConfiguration.class);
private static final Log logger = LogFactory.getLog(ElasticsearchAutoConfiguration.class);
private final ElasticsearchProperties properties;
@@ -103,8 +101,7 @@ public class ElasticsearchAutoConfiguration implements DisposableBean {
}
}
settings.put(this.properties.getProperties());
Node node = new NodeBuilder().settings(settings)
.clusterName(this.properties.getClusterName()).node();
Node node = new NodeBuilder().settings(settings).clusterName(this.properties.getClusterName()).node();
this.releasable = node;
return node.client();
}
@@ -138,8 +135,7 @@ public class ElasticsearchAutoConfiguration implements DisposableBean {
}
catch (NoSuchMethodError ex) {
// Earlier versions of Elasticsearch had a different method name
ReflectionUtils.invokeMethod(
ReflectionUtils.findMethod(Releasable.class, "release"),
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(Releasable.class, "release"),
this.releasable);
}
}

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 @@ 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-2014 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-2015 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-2016 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-2015 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-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.
@@ -80,8 +80,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;
}
@@ -95,34 +94,30 @@ public class MongoDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory,
MongoConverter converter) throws UnknownHostException {
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter converter)
throws UnknownHostException {
return new MongoTemplate(mongoDbFactory, converter);
}
@Bean
@ConditionalOnMissingBean(MongoConverter.class)
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
MongoMappingContext context, BeanFactory beanFactory,
CustomConversions conversions) {
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,
BeanFactory beanFactory, CustomConversions 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(BeanFactory beanFactory,
CustomConversions conversions) throws ClassNotFoundException {
public MongoMappingContext mongoMappingContext(BeanFactory beanFactory, CustomConversions 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.instantiate(strategyClass));
context.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiate(strategyClass));
}
context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
return context;
@@ -130,10 +125,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

@@ -53,10 +53,9 @@ import org.springframework.data.mongodb.repository.support.MongoRepositoryFactor
*/
@Configuration
@ConditionalOnClass({ MongoClient.class, MongoRepository.class })
@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class,
MongoRepositoryConfigurationExtension.class })
@ConditionalOnProperty(prefix = "spring.data.mongodb.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, MongoRepositoryConfigurationExtension.class })
@ConditionalOnProperty(prefix = "spring.data.mongodb.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@Import(MongoRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter(MongoDataAutoConfiguration.class)
public class MongoRepositoriesAutoConfiguration {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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

@@ -53,8 +53,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
* @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)
@SuppressWarnings("deprecation")
@@ -68,10 +67,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) {
@@ -89,11 +86,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,
@@ -105,8 +100,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);
}
@@ -115,11 +109,10 @@ public class Neo4jDataAutoConfiguration {
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ WebMvcConfigurerAdapter.class,
OpenSessionInViewInterceptor.class })
@ConditionalOnClass({ WebMvcConfigurerAdapter.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

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.
@@ -137,8 +137,7 @@ public class Neo4jProperties implements ApplicationContextAware {
}
}
private void configureDriverFromUri(DriverConfiguration driverConfiguration,
String uri) {
private void configureDriverFromUri(DriverConfiguration driverConfiguration, String uri) {
driverConfiguration.setDriverClassName(deduceDriverFromUri());
driverConfiguration.setURI(uri);
}
@@ -156,18 +155,15 @@ public class Neo4jProperties implements ApplicationContextAware {
if ("bolt".equals(scheme)) {
return BOLT_DRIVER;
}
throw new IllegalArgumentException(
"Could not deduce driver to use based on URI '" + uri + "'");
throw new IllegalArgumentException("Could not deduce driver to use based on URI '" + uri + "'");
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException(
"Invalid URI for spring.data.neo4j.uri '" + this.uri + "'", ex);
throw new IllegalArgumentException("Invalid URI for spring.data.neo4j.uri '" + this.uri + "'", ex);
}
}
private void configureDriverWithDefaults(DriverConfiguration driverConfiguration) {
if (getEmbedded().isEnabled()
&& ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) {
if (getEmbedded().isEnabled() && ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) {
driverConfiguration.setDriverClassName(EMBEDDED_DRIVER);
return;
}

View File

@@ -50,10 +50,9 @@ import org.springframework.data.neo4j.repository.support.Neo4jRepositoryFactoryB
*/
@Configuration
@ConditionalOnClass({ Neo4jSession.class, GraphRepository.class })
@ConditionalOnMissingBean({ Neo4jRepositoryFactoryBean.class,
Neo4jRepositoryConfigurationExtension.class })
@ConditionalOnProperty(prefix = "spring.data.neo4j.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean({ Neo4jRepositoryFactoryBean.class, Neo4jRepositoryConfigurationExtension.class })
@ConditionalOnProperty(prefix = "spring.data.neo4j.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@Import(Neo4jRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter(Neo4jDataAutoConfiguration.class)
public class Neo4jRepositoriesAutoConfiguration {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 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 Michael Hunger
*/
class Neo4jRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
class Neo4jRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -87,13 +87,11 @@ public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(RedisConnectionFactory.class)
public JedisConnectionFactory redisConnectionFactory()
throws UnknownHostException {
public JedisConnectionFactory redisConnectionFactory() throws UnknownHostException {
return applyProperties(createJedisConnectionFactory());
}
protected final JedisConnectionFactory applyProperties(
JedisConnectionFactory factory) {
protected final JedisConnectionFactory applyProperties(JedisConnectionFactory factory) {
configureConnection(factory);
if (this.properties.isSsl()) {
factory.setUseSsl(true);
@@ -137,8 +135,7 @@ public class RedisAutoConfiguration {
}
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url,
ex);
throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url, ex);
}
}
@@ -168,8 +165,7 @@ public class RedisAutoConfiguration {
return null;
}
Cluster clusterProperties = this.properties.getCluster();
RedisClusterConfiguration config = new RedisClusterConfiguration(
clusterProperties.getNodes());
RedisClusterConfiguration config = new RedisClusterConfiguration(clusterProperties.getNodes());
if (clusterProperties.getMaxRedirects() != null) {
config.setMaxRedirects(clusterProperties.getMaxRedirects());
@@ -179,24 +175,22 @@ public class RedisAutoConfiguration {
private List<RedisNode> createSentinels(Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<RedisNode>();
for (String node : StringUtils
.commaDelimitedListToStringArray(sentinel.getNodes())) {
for (String node : StringUtils.commaDelimitedListToStringArray(sentinel.getNodes())) {
try {
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "Must be defined as 'host:port'");
nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
}
catch (RuntimeException ex) {
throw new IllegalStateException(
"Invalid redis sentinel " + "property '" + node + "'", ex);
throw new IllegalStateException("Invalid redis sentinel " + "property '" + node + "'", ex);
}
}
return nodes;
}
private JedisConnectionFactory createJedisConnectionFactory() {
JedisPoolConfig poolConfig = (this.properties.getPool() != null)
? jedisPoolConfig() : new JedisPoolConfig();
JedisPoolConfig poolConfig = (this.properties.getPool() != null) ? jedisPoolConfig()
: new JedisPoolConfig();
if (getSentinelConfig() != null) {
return new JedisConnectionFactory(getSentinelConfig(), poolConfig);
}
@@ -226,8 +220,7 @@ public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
@@ -236,8 +229,7 @@ public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);

View File

@@ -38,8 +38,8 @@ import org.springframework.data.redis.repository.support.RedisRepositoryFactoryB
*/
@Configuration
@ConditionalOnClass({ Jedis.class, EnableRedisRepositories.class })
@ConditionalOnProperty(prefix = "spring.data.redis.repositories", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.data.redis.repositories", name = "enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnMissingBean(RedisRepositoryFactoryBean.class)
@Import(RedisRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter(RedisAutoConfiguration.class)

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