Polishing

This commit is contained in:
Sam Brannen 2022-11-08 11:33:57 +01:00
parent aeb35663d4
commit 3438c47744
36 changed files with 190 additions and 228 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,7 +58,7 @@ public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstan
/** /**
* Look up the aspect bean from the {@link BeanFactory} and returns it. * Look up the aspect bean from the {@link BeanFactory} and return it.
* @see #setAspectBeanName * @see #setAspectBeanName
*/ */
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -334,8 +334,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
} }
if (!CollectionUtils.isEmpty(advisors)) { if (!CollectionUtils.isEmpty(advisors)) {
for (Advisor advisor : advisors) { for (Advisor advisor : advisors) {
if (advisor instanceof IntroductionAdvisor) { if (advisor instanceof IntroductionAdvisor introductionAdvisor) {
validateIntroductionAdvisor((IntroductionAdvisor) advisor); validateIntroductionAdvisor(introductionAdvisor);
} }
Assert.notNull(advisor, "Advisor must not be null"); Assert.notNull(advisor, "Advisor must not be null");
this.advisors.add(advisor); this.advisors.add(advisor);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -86,7 +86,7 @@ public class ProxyCreatorSupport extends AdvisedSupport {
/** /**
* Remove the given AdvisedSupportListener from this proxy configuration. * Remove the given AdvisedSupportListener from this proxy configuration.
* @param listener the listener to deregister * @param listener the listener to remove
*/ */
public void removeListener(AdvisedSupportListener listener) { public void removeListener(AdvisedSupportListener listener) {
Assert.notNull(listener, "AdvisedSupportListener must not be null"); Assert.notNull(listener, "AdvisedSupportListener must not be null");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -94,8 +94,8 @@ public abstract class MethodMatchers {
*/ */
public static boolean matches(MethodMatcher mm, Method method, Class<?> targetClass, boolean hasIntroductions) { public static boolean matches(MethodMatcher mm, Method method, Class<?> targetClass, boolean hasIntroductions) {
Assert.notNull(mm, "MethodMatcher must not be null"); Assert.notNull(mm, "MethodMatcher must not be null");
return (mm instanceof IntroductionAwareMethodMatcher ? return (mm instanceof IntroductionAwareMethodMatcher iamm ?
((IntroductionAwareMethodMatcher) mm).matches(method, targetClass, hasIntroductions) : iamm.matches(method, targetClass, hasIntroductions) :
mm.matches(method, targetClass)); mm.matches(method, targetClass));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -63,7 +63,7 @@ public class BeanFactoryRefreshableTargetSource extends AbstractRefreshableTarge
*/ */
@Override @Override
protected final Object freshTarget() { protected final Object freshTarget() {
return this.obtainFreshBean(this.beanFactory, this.beanName); return obtainFreshBean(this.beanFactory, this.beanName);
} }
/** /**

View File

@ -882,7 +882,7 @@ public abstract class BeanUtils {
List<KParameter> parameters = kotlinConstructor.getParameters(); List<KParameter> parameters = kotlinConstructor.getParameters();
Assert.isTrue(args.length <= parameters.size(), Assert.isTrue(args.length <= parameters.size(),
"Number of provided arguments should be less of equals than number of constructor parameters"); "Number of provided arguments must be less than or equal to the number of constructor parameters");
if (parameters.isEmpty()) { if (parameters.isEmpty()) {
return kotlinConstructor.call(); return kotlinConstructor.call();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -112,7 +112,7 @@ public class InjectionPoint {
* @since 5.0 * @since 5.0
*/ */
protected final MethodParameter obtainMethodParameter() { protected final MethodParameter obtainMethodParameter() {
Assert.state(this.methodParameter != null, "Neither Field nor MethodParameter"); Assert.state(this.methodParameter != null, "MethodParameter is not available");
return this.methodParameter; return this.methodParameter;
} }

View File

@ -28,14 +28,11 @@ import org.springframework.util.ReflectionUtils;
/** /**
* Code generator to apply {@link AutowiredArguments}. * Code generator to apply {@link AutowiredArguments}.
* <p> *
* Generates code in the form:<pre class="code">{@code * <p>Generates code in the form: {@code args.get(0), args.get(1)} or
* args.get(0), args.get(1) * {@code args.get(0, String.class), args.get(1, Integer.class)}
* }</pre> or <pre class="code">{@code *
* args.get(0, String.class), args.get(1, Integer.class) * <p>The simpler form is only used if the target method or constructor is
* }</pre>
* <p>
* The simpler form is only used if the target method or constructor is
* unambiguous. * unambiguous.
* *
* @author Phillip Webb * @author Phillip Webb

View File

@ -39,8 +39,8 @@ import org.springframework.util.function.ThrowingConsumer;
* AOT-processed applications as a targeted alternative to the * AOT-processed applications as a targeted alternative to the
* {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor * {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
* AutowiredAnnotationBeanPostProcessor}. * AutowiredAnnotationBeanPostProcessor}.
* <p> *
* When resolving arguments in a native image, the {@link Field} being used must * <p>When resolving arguments in a native image, the {@link Field} being used must
* be marked with an {@link ExecutableMode#INTROSPECT introspection} hint so * be marked with an {@link ExecutableMode#INTROSPECT introspection} hint so
* that field annotations can be read. Full {@link ExecutableMode#INVOKE * that field annotations can be read. Full {@link ExecutableMode#INVOKE
* invocation} hints are only required if the * invocation} hints are only required if the

View File

@ -42,8 +42,8 @@ import org.springframework.util.function.ThrowingConsumer;
* AOT-processed applications as a targeted alternative to the * AOT-processed applications as a targeted alternative to the
* {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor * {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
* AutowiredAnnotationBeanPostProcessor}. * AutowiredAnnotationBeanPostProcessor}.
* <p> *
* When resolving arguments in a native image, the {@link Method} being used * <p>When resolving arguments in a native image, the {@link Method} being used
* must be marked with an {@link ExecutableMode#INTROSPECT introspection} hint * must be marked with an {@link ExecutableMode#INTROSPECT introspection} hint
* so that field annotations can be read. Full {@link ExecutableMode#INVOKE * so that field annotations can be read. Full {@link ExecutableMode#INVOKE
* invocation} hints are only required if the * invocation} hints are only required if the
@ -205,9 +205,8 @@ public final class AutowiredMethodArgumentsResolver extends AutowiredElementReso
private Method getMethod(RegisteredBean registeredBean) { private Method getMethod(RegisteredBean registeredBean) {
Method method = ReflectionUtils.findMethod(registeredBean.getBeanClass(), Method method = ReflectionUtils.findMethod(registeredBean.getBeanClass(),
this.methodName, this.parameterTypes); this.methodName, this.parameterTypes);
Assert.notNull(method, Assert.notNull(method, () ->
() -> String.format( "Method '%s' with parameter types [%s] declared on %s could not be found.".formatted(
"Method '%s' with parameter types [%s] declared on %s",
this.methodName, toCommaSeparatedNames(this.parameterTypes), this.methodName, toCommaSeparatedNames(this.parameterTypes),
registeredBean.getBeanClass().getName())); registeredBean.getBeanClass().getName()));
return method; return method;

View File

@ -61,8 +61,8 @@ import org.springframework.util.function.ThrowingSupplier;
* handles resolution of {@link AutowiredArguments} if necessary. Typically used * handles resolution of {@link AutowiredArguments} if necessary. Typically used
* in AOT-processed applications as a targeted alternative to the reflection * in AOT-processed applications as a targeted alternative to the reflection
* based injection. * based injection.
* <p> *
* If no {@code generator} is provided, reflection is used to instantiate the * <p>If no {@code generator} is provided, reflection is used to instantiate the
* bean instance, and full {@link ExecutableMode#INVOKE invocation} hints are * bean instance, and full {@link ExecutableMode#INVOKE invocation} hints are
* contributed. Multiple generator callback styles are supported: * contributed. Multiple generator callback styles are supported:
* <ul> * <ul>
@ -75,7 +75,7 @@ import org.springframework.util.function.ThrowingSupplier;
* <li>A supplier when a method reference can be used</li> * <li>A supplier when a method reference can be used</li>
* </ul> * </ul>
* Generator callbacks handle checked exceptions so that the caller does not * Generator callbacks handle checked exceptions so that the caller does not
* have to deal with it. * have to deal with them.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
@ -113,10 +113,8 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
Class<?>... parameterTypes) { Class<?>... parameterTypes) {
Assert.notNull(parameterTypes, "'parameterTypes' must not be null"); Assert.notNull(parameterTypes, "'parameterTypes' must not be null");
Assert.noNullElements(parameterTypes, Assert.noNullElements(parameterTypes, "'parameterTypes' must not contain null elements");
"'parameterTypes' must not contain null elements"); return new BeanInstanceSupplier<>(new ConstructorLookup(parameterTypes), null, null);
return new BeanInstanceSupplier<>(
new ConstructorLookup(parameterTypes), null, null);
} }
/** /**
@ -134,8 +132,7 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
Assert.notNull(declaringClass, "'declaringClass' must not be null"); Assert.notNull(declaringClass, "'declaringClass' must not be null");
Assert.hasText(methodName, "'methodName' must not be empty"); Assert.hasText(methodName, "'methodName' must not be empty");
Assert.notNull(parameterTypes, "'parameterTypes' must not be null"); Assert.notNull(parameterTypes, "'parameterTypes' must not be null");
Assert.noNullElements(parameterTypes, Assert.noNullElements(parameterTypes, "'parameterTypes' must not contain null elements");
"'parameterTypes' must not contain null elements");
return new BeanInstanceSupplier<>( return new BeanInstanceSupplier<>(
new FactoryMethodLookup(declaringClass, methodName, parameterTypes), new FactoryMethodLookup(declaringClass, methodName, parameterTypes),
null, null); null, null);
@ -172,8 +169,8 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
public BeanInstanceSupplier<T> withGenerator( public BeanInstanceSupplier<T> withGenerator(
ThrowingFunction<RegisteredBean, T> generator) { ThrowingFunction<RegisteredBean, T> generator) {
Assert.notNull(generator, "'generator' must not be null"); Assert.notNull(generator, "'generator' must not be null");
return new BeanInstanceSupplier<>(this.lookup, (registeredBean, args) -> return new BeanInstanceSupplier<>(this.lookup,
generator.apply(registeredBean), this.shortcuts); (registeredBean, args) -> generator.apply(registeredBean), this.shortcuts);
} }
/** /**
@ -186,8 +183,8 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
*/ */
public BeanInstanceSupplier<T> withGenerator(ThrowingSupplier<T> generator) { public BeanInstanceSupplier<T> withGenerator(ThrowingSupplier<T> generator) {
Assert.notNull(generator, "'generator' must not be null"); Assert.notNull(generator, "'generator' must not be null");
return new BeanInstanceSupplier<>(this.lookup, (registeredBean, args) -> return new BeanInstanceSupplier<>(this.lookup,
generator.get(), this.shortcuts); (registeredBean, args) -> generator.get(), this.shortcuts);
} }
/** /**
@ -208,11 +205,10 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
Executable executable = this.lookup.get(registeredBean); Executable executable = this.lookup.get(registeredBean);
AutowiredArguments arguments = resolveArguments(registeredBean, executable); AutowiredArguments arguments = resolveArguments(registeredBean, executable);
if (this.generator != null) { if (this.generator != null) {
return invokeBeanSupplier(executable, () -> return invokeBeanSupplier(executable, () -> this.generator.apply(registeredBean, arguments));
this.generator.apply(registeredBean, arguments));
} }
return invokeBeanSupplier(executable, () -> return invokeBeanSupplier(executable,
instantiate(registeredBean.getBeanFactory(), executable, arguments.toArray())); () -> instantiate(registeredBean.getBeanFactory(), executable, arguments.toArray()));
} }
private T invokeBeanSupplier(Executable executable, ThrowingSupplier<T> beanSupplier) { private T invokeBeanSupplier(Executable executable, ThrowingSupplier<T> beanSupplier) {
@ -247,19 +243,15 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
return resolveArguments(registeredBean, this.lookup.get(registeredBean)); return resolveArguments(registeredBean, this.lookup.get(registeredBean));
} }
private AutowiredArguments resolveArguments(RegisteredBean registeredBean, private AutowiredArguments resolveArguments(RegisteredBean registeredBean,Executable executable) {
Executable executable) { Assert.isInstanceOf(AbstractAutowireCapableBeanFactory.class, registeredBean.getBeanFactory());
Assert.isInstanceOf(AbstractAutowireCapableBeanFactory.class,
registeredBean.getBeanFactory());
String beanName = registeredBean.getBeanName(); String beanName = registeredBean.getBeanName();
Class<?> beanClass = registeredBean.getBeanClass(); Class<?> beanClass = registeredBean.getBeanClass();
AbstractAutowireCapableBeanFactory beanFactory = (AbstractAutowireCapableBeanFactory) registeredBean AbstractAutowireCapableBeanFactory beanFactory =
.getBeanFactory(); (AbstractAutowireCapableBeanFactory) registeredBean.getBeanFactory();
RootBeanDefinition mergedBeanDefinition = registeredBean RootBeanDefinition mergedBeanDefinition = registeredBean.getMergedBeanDefinition();
.getMergedBeanDefinition(); int startIndex = (executable instanceof Constructor<?> constructor &&
int startIndex = (executable instanceof Constructor<?> constructor ClassUtils.isInnerClass(constructor.getDeclaringClass())) ? 1 : 0;
&& ClassUtils.isInnerClass(constructor.getDeclaringClass())) ? 1 : 0;
int parameterCount = executable.getParameterCount(); int parameterCount = executable.getParameterCount();
Object[] resolved = new Object[parameterCount - startIndex]; Object[] resolved = new Object[parameterCount - startIndex];
Assert.isTrue(this.shortcuts == null || this.shortcuts.length == resolved.length, Assert.isTrue(this.shortcuts == null || this.shortcuts.length == resolved.length,
@ -269,10 +261,8 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
beanName, mergedBeanDefinition); beanName, mergedBeanDefinition);
for (int i = startIndex; i < parameterCount; i++) { for (int i = startIndex; i < parameterCount; i++) {
MethodParameter parameter = getMethodParameter(executable, i); MethodParameter parameter = getMethodParameter(executable, i);
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor( DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(parameter, true);
parameter, true); String shortcut = (this.shortcuts != null) ? this.shortcuts[i - startIndex] : null;
String shortcut = (this.shortcuts != null) ? this.shortcuts[i - startIndex]
: null;
if (shortcut != null) { if (shortcut != null) {
dependencyDescriptor = new ShortcutDependencyDescriptor( dependencyDescriptor = new ShortcutDependencyDescriptor(
dependencyDescriptor, shortcut, beanClass); dependencyDescriptor, shortcut, beanClass);
@ -303,13 +293,10 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
ConstructorArgumentValues resolved = new ConstructorArgumentValues(); ConstructorArgumentValues resolved = new ConstructorArgumentValues();
if (mergedBeanDefinition.hasConstructorArgumentValues()) { if (mergedBeanDefinition.hasConstructorArgumentValues()) {
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver( BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(
beanFactory, beanName, mergedBeanDefinition, beanFactory, beanName, mergedBeanDefinition, beanFactory.getTypeConverter());
beanFactory.getTypeConverter()); ConstructorArgumentValues values = mergedBeanDefinition.getConstructorArgumentValues();
ConstructorArgumentValues values = mergedBeanDefinition
.getConstructorArgumentValues();
values.getIndexedArgumentValues().forEach((index, valueHolder) -> { values.getIndexedArgumentValues().forEach((index, valueHolder) -> {
ValueHolder resolvedValue = resolveArgumentValue(valueResolver, ValueHolder resolvedValue = resolveArgumentValue(valueResolver, valueHolder);
valueHolder);
resolved.addIndexedArgumentValue(index, resolvedValue); resolved.addIndexedArgumentValue(index, resolvedValue);
}); });
} }
@ -333,15 +320,14 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
@Nullable @Nullable
private Object resolveArgument(AbstractAutowireCapableBeanFactory beanFactory, private Object resolveArgument(AbstractAutowireCapableBeanFactory beanFactory,
String beanName, Set<String> autowiredBeans, MethodParameter parameter, String beanName, Set<String> autowiredBeans, MethodParameter parameter,
DependencyDescriptor dependencyDescriptor, DependencyDescriptor dependencyDescriptor, @Nullable ValueHolder argumentValue) {
@Nullable ValueHolder argumentValue) {
TypeConverter typeConverter = beanFactory.getTypeConverter(); TypeConverter typeConverter = beanFactory.getTypeConverter();
Class<?> parameterType = parameter.getParameterType(); Class<?> parameterType = parameter.getParameterType();
if (argumentValue != null) { if (argumentValue != null) {
return (!argumentValue.isConverted()) ? typeConverter return (!argumentValue.isConverted()) ?
.convertIfNecessary(argumentValue.getValue(), parameterType) typeConverter.convertIfNecessary(argumentValue.getValue(), parameterType) :
: argumentValue.getConvertedValue(); argumentValue.getConvertedValue();
} }
try { try {
try { try {
@ -387,9 +373,7 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
"Unsupported executable " + executable.getClass().getName()); "Unsupported executable " + executable.getClass().getName());
} }
private Object instantiate(Constructor<?> constructor, Object[] arguments) private Object instantiate(Constructor<?> constructor, Object[] arguments) throws Exception {
throws Exception {
Class<?> declaringClass = constructor.getDeclaringClass(); Class<?> declaringClass = constructor.getDeclaringClass();
if (ClassUtils.isInnerClass(declaringClass)) { if (ClassUtils.isInnerClass(declaringClass)) {
Object enclosingInstance = createInstance(declaringClass.getEnclosingClass()); Object enclosingInstance = createInstance(declaringClass.getEnclosingClass());
@ -428,6 +412,10 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
} }
private static String toCommaSeparatedNames(Class<?>... parameterTypes) {
return Arrays.stream(parameterTypes).map(Class::getName).collect(Collectors.joining(", "));
}
/** /**
* Performs lookup of the {@link Executable}. * Performs lookup of the {@link Executable}.
*/ */
@ -435,11 +423,6 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
abstract Executable get(RegisteredBean registeredBean); abstract Executable get(RegisteredBean registeredBean);
final String toCommaSeparatedNames(Class<?>... parameterTypes) {
return Arrays.stream(parameterTypes).map(Class::getName)
.collect(Collectors.joining(", "));
}
} }
@ -460,20 +443,20 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
public Executable get(RegisteredBean registeredBean) { public Executable get(RegisteredBean registeredBean) {
Class<?> beanClass = registeredBean.getBeanClass(); Class<?> beanClass = registeredBean.getBeanClass();
try { try {
Class<?>[] actualParameterTypes = (!ClassUtils.isInnerClass(beanClass)) Class<?>[] actualParameterTypes = (!ClassUtils.isInnerClass(beanClass)) ?
? this.parameterTypes : ObjectUtils.addObjectToArray( this.parameterTypes : ObjectUtils.addObjectToArray(
this.parameterTypes, beanClass.getEnclosingClass(), 0); this.parameterTypes, beanClass.getEnclosingClass(), 0);
return beanClass.getDeclaredConstructor(actualParameterTypes); return beanClass.getDeclaredConstructor(actualParameterTypes);
} }
catch (NoSuchMethodException ex) { catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(String.format( throw new IllegalArgumentException(
"%s cannot be found on %s", this, beanClass.getName()), ex); "%s cannot be found on %s".formatted(this, beanClass.getName()), ex);
} }
} }
@Override @Override
public String toString() { public String toString() {
return String.format("Constructor with parameter types [%s]", return "Constructor with parameter types [%s]".formatted(
toCommaSeparatedNames(this.parameterTypes)); toCommaSeparatedNames(this.parameterTypes));
} }
@ -508,14 +491,13 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
Method get() { Method get() {
Method method = ReflectionUtils.findMethod(this.declaringClass, Method method = ReflectionUtils.findMethod(this.declaringClass,
this.methodName, this.parameterTypes); this.methodName, this.parameterTypes);
Assert.notNull(method, () -> String.format("%s cannot be found", this)); Assert.notNull(method, () -> "%s cannot be found".formatted(this));
return method; return method;
} }
@Override @Override
public String toString() { public String toString() {
return String.format( return "Factory method '%s' with parameter types [%s] declared on %s".formatted(
"Factory method '%s' with parameter types [%s] declared on %s",
this.methodName, toCommaSeparatedNames(this.parameterTypes), this.methodName, toCommaSeparatedNames(this.parameterTypes),
this.declaringClass); this.declaringClass);
} }

View File

@ -33,7 +33,7 @@ import org.springframework.util.Assert;
/** /**
* A {@link BeanRegistrationCodeFragments} decorator implementation. Typically * A {@link BeanRegistrationCodeFragments} decorator implementation. Typically
* used when part of the default code fragments have to customized, by extending * used when part of the default code fragments have to customized, by extending
* this class and use it as part of * this class and using it as part of
* {@link BeanRegistrationAotContribution#withCustomCodeFragments(UnaryOperator)}. * {@link BeanRegistrationAotContribution#withCustomCodeFragments(UnaryOperator)}.
* *
* @author Phillip Webb * @author Phillip Webb
@ -42,7 +42,6 @@ import org.springframework.util.Assert;
*/ */
public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationCodeFragments { public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationCodeFragments {
private final BeanRegistrationCodeFragments delegate; private final BeanRegistrationCodeFragments delegate;
@ -52,9 +51,7 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
} }
@Override @Override
public ClassName getTarget(RegisteredBean registeredBean, public ClassName getTarget(RegisteredBean registeredBean, Executable constructorOrFactoryMethod) {
Executable constructorOrFactoryMethod) {
return this.delegate.getTarget(registeredBean, constructorOrFactoryMethod); return this.delegate.getTarget(registeredBean, constructorOrFactoryMethod);
} }
@ -64,7 +61,6 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
return this.delegate.generateNewBeanDefinitionCode(generationContext, return this.delegate.generateNewBeanDefinitionCode(generationContext,
beanType, beanRegistrationCode); beanType, beanRegistrationCode);
} }
@Override @Override
@ -75,7 +71,6 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
return this.delegate.generateSetBeanDefinitionPropertiesCode( return this.delegate.generateSetBeanDefinitionPropertiesCode(
generationContext, beanRegistrationCode, beanDefinition, attributeFilter); generationContext, beanRegistrationCode, beanDefinition, attributeFilter);
} }
@Override @Override
@ -101,8 +96,7 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
public CodeBlock generateReturnCode(GenerationContext generationContext, public CodeBlock generateReturnCode(GenerationContext generationContext,
BeanRegistrationCode beanRegistrationCode) { BeanRegistrationCode beanRegistrationCode) {
return this.delegate.generateReturnCode(generationContext, return this.delegate.generateReturnCode(generationContext, beanRegistrationCode);
beanRegistrationCode);
} }
} }

View File

@ -45,7 +45,7 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
} }
/** /**
* Gets the supplied instance. * Get the supplied instance.
* @param registeredBean the registered bean requesting the instance * @param registeredBean the registered bean requesting the instance
* @return the supplied instance * @return the supplied instance
* @throws Exception on error * @throws Exception on error
@ -55,7 +55,7 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
/** /**
* Return the factory method that this supplier uses to create the * Return the factory method that this supplier uses to create the
* instance, or {@code null} if it is not known or this supplier uses * instance, or {@code null} if it is not known or this supplier uses
* another mean. * another means.
* @return the factory method used to create the instance, or {@code null} * @return the factory method used to create the instance, or {@code null}
*/ */
@Nullable @Nullable
@ -65,7 +65,7 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
/** /**
* Return a composed instance supplier that first obtains the instance from * Return a composed instance supplier that first obtains the instance from
* this supplier, and then applied the {@code after} function to obtain the * this supplier and then applies the {@code after} function to obtain the
* result. * result.
* @param <V> the type of output of the {@code after} function, and of the * @param <V> the type of output of the {@code after} function, and of the
* composed function * composed function
@ -74,7 +74,7 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
*/ */
default <V> InstanceSupplier<V> andThen( default <V> InstanceSupplier<V> andThen(
ThrowingBiFunction<RegisteredBean, ? super T, ? extends V> after) { ThrowingBiFunction<RegisteredBean, ? super T, ? extends V> after) {
Assert.notNull(after, "After must not be null"); Assert.notNull(after, "'after' function must not be null");
return new InstanceSupplier<V>() { return new InstanceSupplier<V>() {
@Override @Override
@ -135,10 +135,9 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
} }
/** /**
* Lambda friendly method that can be used to create a * Lambda friendly method that can be used to create an
* {@link InstanceSupplier} and add post processors in a single call. For * {@link InstanceSupplier} and add post processors in a single call. For
* example: {@code * example: {@code InstanceSupplier.of(registeredBean -> ...).andThen(...)}.
* InstanceSupplier.of(registeredBean -> ...).andThen(...)}.
* @param <T> the type of instance supplied by this supplier * @param <T> the type of instance supplied by this supplier
* @param instanceSupplier the source instance supplier * @param instanceSupplier the source instance supplier
* @return a new {@link InstanceSupplier} * @return a new {@link InstanceSupplier}

View File

@ -74,12 +74,11 @@ class AutowiredMethodArgumentsResolverTests {
@Test @Test
void resolveWhenMethodIsMissingThrowsException() { void resolveWhenMethodIsMissingThrowsException() {
RegisteredBean registeredBean = registerTestBean(this.beanFactory); RegisteredBean registeredBean = registerTestBean(this.beanFactory);
AutowiredMethodArgumentsResolver resolver = AutowiredMethodArgumentsResolver.forMethod("missing", InputStream.class);
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> AutowiredMethodArgumentsResolver .isThrownBy(() -> resolver.resolve(registeredBean))
.forMethod("missing", InputStream.class).resolve(registeredBean)) .withMessage("Method 'missing' with parameter types [java.io.InputStream] declared on %s could not be found.",
.withMessage( TestBean.class.getName());
"Method 'missing' with parameter types [java.io.InputStream] declared on "
+ TestBean.class.getName());
} }
@Test @Test

View File

@ -61,7 +61,7 @@ class InstanceSupplierTests {
InstanceSupplier<String> supplier = registeredBean -> "test"; InstanceSupplier<String> supplier = registeredBean -> "test";
ThrowingBiFunction<RegisteredBean, String, String> after = null; ThrowingBiFunction<RegisteredBean, String, String> after = null;
assertThatIllegalArgumentException().isThrownBy(() -> supplier.andThen(after)) assertThatIllegalArgumentException().isThrownBy(() -> supplier.andThen(after))
.withMessage("After must not be null"); .withMessage("'after' function must not be null");
} }
@Test @Test

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -132,7 +132,7 @@ public class Constants {
/** /**
* Parse the given String (upper or lower case accepted) and return * Parse the given String (upper or lower case accepted) and return
* the appropriate value if it's the name of a constant field in the * the appropriate value if it's the name of a constant field in the
* class that we're analysing. * class that we're analyzing.
* @param code the name of the field (never {@code null}) * @param code the name of the field (never {@code null})
* @return the Object value * @return the Object value
* @throws ConstantException if there's no such field * @throws ConstantException if there's no such field

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -169,10 +169,7 @@ public final class Conventions {
Assert.notNull(method, "Method must not be null"); Assert.notNull(method, "Method must not be null");
if (Object.class == resolvedType) { if (Object.class == resolvedType) {
if (value == null) { Assert.notNull(value, "Cannot generate variable name for an Object return type with null value");
throw new IllegalArgumentException(
"Cannot generate variable name for an Object return type with null value");
}
return getVariableName(value); return getVariableName(value);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -94,7 +94,7 @@ public final class ReactiveTypeDescriptor {
/** /**
* Return an empty-value instance for the underlying reactive or async type. * Return an empty-value instance for the underlying reactive or async type.
* Use of this type implies {@link #supportsEmpty()} is {@code true}. * <p>Use of this type implies {@link #supportsEmpty()} is {@code true}.
*/ */
public Object getEmptyValue() { public Object getEmptyValue() {
Assert.state(this.emptyValueSupplier != null, "Empty values not supported"); Assert.state(this.emptyValueSupplier != null, "Empty values not supported");

View File

@ -425,7 +425,7 @@ public class DefaultDataBuffer implements DataBuffer {
* @see io.netty.buffer.AbstractByteBufAllocator#calculateNewCapacity(int, int) * @see io.netty.buffer.AbstractByteBufAllocator#calculateNewCapacity(int, int)
*/ */
private int calculateCapacity(int neededCapacity) { private int calculateCapacity(int neededCapacity) {
Assert.isTrue(neededCapacity >= 0, "'neededCapacity' must >= 0"); Assert.isTrue(neededCapacity >= 0, "'neededCapacity' must be >= 0");
if (neededCapacity == CAPACITY_THRESHOLD) { if (neededCapacity == CAPACITY_THRESHOLD) {
return CAPACITY_THRESHOLD; return CAPACITY_THRESHOLD;

View File

@ -28,7 +28,6 @@ import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
/** /**
* Implementation of the {@code DataBuffer} interface that wraps a Netty 5 * Implementation of the {@code DataBuffer} interface that wraps a Netty 5
* {@link Buffer}. Typically constructed with {@link Netty5DataBufferFactory}. * {@link Buffer}. Typically constructed with {@link Netty5DataBufferFactory}.
@ -37,8 +36,7 @@ import org.springframework.util.ObjectUtils;
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 6.0 * @since 6.0
*/ */
public final class Netty5DataBuffer implements CloseableDataBuffer, public final class Netty5DataBuffer implements CloseableDataBuffer, TouchableDataBuffer {
TouchableDataBuffer {
private final Buffer buffer; private final Buffer buffer;
@ -51,7 +49,7 @@ public final class Netty5DataBuffer implements CloseableDataBuffer,
*/ */
Netty5DataBuffer(Buffer buffer, Netty5DataBufferFactory dataBufferFactory) { Netty5DataBuffer(Buffer buffer, Netty5DataBufferFactory dataBufferFactory) {
Assert.notNull(buffer, "Buffer must not be null"); Assert.notNull(buffer, "Buffer must not be null");
Assert.notNull(dataBufferFactory, "NettyDataBufferFactory must not be null"); Assert.notNull(dataBufferFactory, "Netty5DataBufferFactory must not be null");
this.buffer = buffer; this.buffer = buffer;
this.dataBufferFactory = dataBufferFactory; this.dataBufferFactory = dataBufferFactory;
} }
@ -150,7 +148,7 @@ public final class Netty5DataBuffer implements CloseableDataBuffer,
@Override @Override
public DataBuffer ensureWritable(int capacity) { public DataBuffer ensureWritable(int capacity) {
Assert.isTrue(capacity >= 0, "Capacity must be larger than 0"); Assert.isTrue(capacity >= 0, "Capacity must be >= 0");
this.buffer.ensureWritable(capacity); this.buffer.ensureWritable(capacity);
return this; return this;
} }
@ -328,6 +326,7 @@ public final class Netty5DataBuffer implements CloseableDataBuffer,
} }
@Override
public boolean equals(@Nullable Object other) { public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof Netty5DataBuffer dataBuffer && return (this == other || (other instanceof Netty5DataBuffer dataBuffer &&
this.buffer.equals(dataBuffer.buffer))); this.buffer.equals(dataBuffer.buffer)));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -146,7 +146,7 @@ public abstract class AbstractMethodMessageHandler<T>
* Configure custom resolvers for handler method arguments. * Configure custom resolvers for handler method arguments.
*/ */
public void setArgumentResolverConfigurer(ArgumentResolverConfigurer configurer) { public void setArgumentResolverConfigurer(ArgumentResolverConfigurer configurer) {
Assert.notNull(configurer, "HandlerMethodArgumentResolver is required"); Assert.notNull(configurer, "ArgumentResolverConfigurer is required");
this.argumentResolverConfigurer = configurer; this.argumentResolverConfigurer = configurer;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -36,11 +36,11 @@ public class ArgumentResolverConfigurer {
/** /**
* Configure resolvers for custom handler method arguments. * Configure resolvers for custom handler method arguments.
* @param resolver the resolvers to add * @param resolvers the resolvers to add
*/ */
public void addCustomResolver(HandlerMethodArgumentResolver... resolver) { public void addCustomResolver(HandlerMethodArgumentResolver... resolvers) {
Assert.notNull(resolver, "'resolvers' must not be null"); Assert.notNull(resolvers, "'resolvers' must not be null");
this.customResolvers.addAll(Arrays.asList(resolver)); this.customResolvers.addAll(Arrays.asList(resolvers));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -171,7 +171,8 @@ final class DefaultRSocketRequester implements RSocketRequester {
Assert.notNull(producer, "'producer' must not be null"); Assert.notNull(producer, "'producer' must not be null");
Assert.notNull(elementClass, "'elementClass' must not be null"); Assert.notNull(elementClass, "'elementClass' must not be null");
ReactiveAdapter adapter = getAdapter(producer.getClass()); ReactiveAdapter adapter = getAdapter(producer.getClass());
Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); Assert.notNull(adapter, () -> "'producer' type is unknown to ReactiveAdapterRegistry: " +
producer.getClass().getName());
createPayload(adapter.toPublisher(producer), ResolvableType.forClass(elementClass)); createPayload(adapter.toPublisher(producer), ResolvableType.forClass(elementClass));
return this; return this;
} }
@ -186,7 +187,8 @@ final class DefaultRSocketRequester implements RSocketRequester {
Assert.notNull(producer, "'producer' must not be null"); Assert.notNull(producer, "'producer' must not be null");
Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null"); Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null");
ReactiveAdapter adapter = getAdapter(producer.getClass()); ReactiveAdapter adapter = getAdapter(producer.getClass());
Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); Assert.notNull(adapter, () -> "'producer' type is unknown to ReactiveAdapterRegistry: " +
producer.getClass().getName());
createPayload(adapter.toPublisher(producer), ResolvableType.forType(elementTypeRef)); createPayload(adapter.toPublisher(producer), ResolvableType.forType(elementTypeRef));
return this; return this;
} }

View File

@ -78,8 +78,8 @@ final class MetadataEncoder {
this.strategies = strategies; this.strategies = strategies;
this.isComposite = this.metadataMimeType.toString().equals( this.isComposite = this.metadataMimeType.toString().equals(
WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
this.allocator = bufferFactory() instanceof NettyDataBufferFactory ? this.allocator = bufferFactory() instanceof NettyDataBufferFactory nettyDBF ?
((NettyDataBufferFactory) bufferFactory()).getByteBufAllocator() : ByteBufAllocator.DEFAULT; nettyDBF.getByteBufAllocator() : ByteBufAllocator.DEFAULT;
} }
@ -193,7 +193,7 @@ final class MetadataEncoder {
Object value = entry.value(); Object value = entry.value();
io.rsocket.metadata.CompositeMetadataCodec.encodeAndAddMetadata( io.rsocket.metadata.CompositeMetadataCodec.encodeAndAddMetadata(
composite, this.allocator, entry.mimeType().toString(), composite, this.allocator, entry.mimeType().toString(),
value instanceof ByteBuf ? (ByteBuf) value : PayloadUtils.asByteBuf(encodeEntry(entry))); value instanceof ByteBuf byteBuf ? byteBuf : PayloadUtils.asByteBuf(encodeEntry(entry)));
}); });
return asDataBuffer(composite); return asDataBuffer(composite);
} }
@ -232,8 +232,8 @@ final class MetadataEncoder {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> DataBuffer encodeEntry(Object value, MimeType mimeType) { private <T> DataBuffer encodeEntry(Object value, MimeType mimeType) {
if (value instanceof ByteBuf) { if (value instanceof ByteBuf byteBuf) {
return asDataBuffer((ByteBuf) value); return asDataBuffer(byteBuf);
} }
ResolvableType type = ResolvableType.forInstance(value); ResolvableType type = ResolvableType.forInstance(value);
Encoder<T> encoder = this.strategies.encoder(type, mimeType); Encoder<T> encoder = this.strategies.encoder(type, mimeType);
@ -242,8 +242,8 @@ final class MetadataEncoder {
} }
private DataBuffer asDataBuffer(ByteBuf byteBuf) { private DataBuffer asDataBuffer(ByteBuf byteBuf) {
if (bufferFactory() instanceof NettyDataBufferFactory) { if (bufferFactory() instanceof NettyDataBufferFactory nettyDBF) {
return ((NettyDataBufferFactory) bufferFactory()).wrap(byteBuf); return nettyDBF.wrap(byteBuf);
} }
else { else {
DataBuffer buffer = bufferFactory().wrap(byteBuf.nioBuffer()); DataBuffer buffer = bufferFactory().wrap(byteBuf.nioBuffer());
@ -257,7 +257,7 @@ final class MetadataEncoder {
List<Mono<?>> valueMonos = new ArrayList<>(); List<Mono<?>> valueMonos = new ArrayList<>();
this.metadataEntries.forEach(entry -> { this.metadataEntries.forEach(entry -> {
Object v = entry.value(); Object v = entry.value();
valueMonos.add(v instanceof Mono ? (Mono<?>) v : Mono.just(v)); valueMonos.add(v instanceof Mono<?> mono ? mono : Mono.just(v));
}); });
return Mono.zip(valueMonos, values -> { return Mono.zip(valueMonos, values -> {
List<MetadataEntry> result = new ArrayList<>(values.length); List<MetadataEntry> result = new ArrayList<>(values.length);

View File

@ -31,14 +31,15 @@ import org.springframework.util.ReflectionUtils;
/** /**
* Internal code generator that can inject a value into a field or single-arg * Internal code generator that can inject a value into a field or single-arg
* method. * method.
* <p> *
* Generates code in the form:<pre class="code">{@code * <p>Generates code in the form:
* <pre class="code">{@code
* instance.age = value; * instance.age = value;
* }</pre> or <pre class="code">{@code * }</pre> or <pre class="code">{@code
* instance.setAge(value); * instance.setAge(value);
* }</pre> * }</pre>
* <p> *
* Will also generate reflection based injection and register hints if the * <p>Will also generate reflection based injection and register hints if the
* member is not visible. * member is not visible.
* *
* @author Phillip Webb * @author Phillip Webb
@ -59,18 +60,14 @@ class InjectionCodeGenerator {
} }
CodeBlock generateInjectionCode(Member member, String instanceVariable, CodeBlock generateInjectionCode(Member member, String instanceVariable, CodeBlock resourceToInject) {
CodeBlock resourceToInject) {
if (member instanceof Field field) { if (member instanceof Field field) {
return generateFieldInjectionCode(field, instanceVariable, resourceToInject); return generateFieldInjectionCode(field, instanceVariable, resourceToInject);
} }
if (member instanceof Method method) { if (member instanceof Method method) {
return generateMethodInjectionCode(method, instanceVariable, return generateMethodInjectionCode(method, instanceVariable, resourceToInject);
resourceToInject);
} }
throw new IllegalStateException( throw new IllegalStateException("Unsupported member type " + member.getClass().getName());
"Unsupported member type " + member.getClass().getName());
} }
private CodeBlock generateFieldInjectionCode(Field field, String instanceVariable, private CodeBlock generateFieldInjectionCode(Field field, String instanceVariable,
@ -87,8 +84,7 @@ class InjectionCodeGenerator {
"field", instanceVariable, resourceToInject); "field", instanceVariable, resourceToInject);
} }
else { else {
code.addStatement("$L.$L = $L", instanceVariable, field.getName(), code.addStatement("$L.$L = $L", instanceVariable, field.getName(), resourceToInject);
resourceToInject);
} }
return code.build(); return code.build();
} }
@ -105,14 +101,12 @@ class InjectionCodeGenerator {
code.addStatement("$T method = $T.findMethod($T.class, $S, $T.class)", code.addStatement("$T method = $T.findMethod($T.class, $S, $T.class)",
Method.class, ReflectionUtils.class, method.getDeclaringClass(), Method.class, ReflectionUtils.class, method.getDeclaringClass(),
method.getName(), method.getParameterTypes()[0]); method.getName(), method.getParameterTypes()[0]);
code.addStatement("$T.makeAccessible($L)", ReflectionUtils.class, code.addStatement("$T.makeAccessible($L)", ReflectionUtils.class, "method");
"method");
code.addStatement("$T.invokeMethod($L, $L, $L)", ReflectionUtils.class, code.addStatement("$T.invokeMethod($L, $L, $L)", ReflectionUtils.class,
"method", instanceVariable, resourceToInject); "method", instanceVariable, resourceToInject);
} }
else { else {
code.addStatement("$L.$L($L)", instanceVariable, method.getName(), code.addStatement("$L.$L($L)", instanceVariable, method.getName(), resourceToInject);
resourceToInject);
} }
return code.build(); return code.build();
} }

View File

@ -200,7 +200,7 @@ public abstract class AbstractRoutingConnectionFactory implements ConnectionFact
* in the {@link #setTargetConnectionFactories targetConnectionFactories} map, * in the {@link #setTargetConnectionFactories targetConnectionFactories} map,
* falls back to the specified {@link #setDefaultTargetConnectionFactory default * falls back to the specified {@link #setDefaultTargetConnectionFactory default
* target ConnectionFactory} if necessary. * target ConnectionFactory} if necessary.
* @return {@link Mono} emitting the current {@link ConnectionFactory} as * @return {@link Mono} that emits the current {@link ConnectionFactory} as
* per {@link #determineCurrentLookupKey()} * per {@link #determineCurrentLookupKey()}
* @see #determineCurrentLookupKey() * @see #determineCurrentLookupKey()
*/ */

View File

@ -43,7 +43,6 @@ import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeType; import org.springframework.util.MimeType;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
/** /**
@ -236,7 +235,7 @@ public final class MockServerHttpRequest extends AbstractServerHttpRequest {
*/ */
@Deprecated(since = "6.0") @Deprecated(since = "6.0")
public static BodyBuilder method(String httpMethod, String uri, Object... vars) { public static BodyBuilder method(String httpMethod, String uri, Object... vars) {
Assert.isTrue(StringUtils.hasText(httpMethod), "HTTP method is required."); Assert.hasText(httpMethod, "HTTP method is required.");
return new DefaultBodyBuilder(HttpMethod.valueOf(httpMethod), toUri(uri, vars)); return new DefaultBodyBuilder(HttpMethod.valueOf(httpMethod), toUri(uri, vars));
} }

View File

@ -549,11 +549,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
public void setParameters(Map<String, ?> params) { public void setParameters(Map<String, ?> params) {
Assert.notNull(params, "Parameter map must not be null"); Assert.notNull(params, "Parameter map must not be null");
params.forEach((key, value) -> { params.forEach((key, value) -> {
if (value instanceof String) { if (value instanceof String str) {
setParameter(key, (String) value); setParameter(key, str);
} }
else if (value instanceof String[]) { else if (value instanceof String[] strings) {
setParameter(key, (String[]) value); setParameter(key, strings);
} }
else { else {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -598,11 +598,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
public void addParameters(Map<String, ?> params) { public void addParameters(Map<String, ?> params) {
Assert.notNull(params, "Parameter map must not be null"); Assert.notNull(params, "Parameter map must not be null");
params.forEach((key, value) -> { params.forEach((key, value) -> {
if (value instanceof String) { if (value instanceof String str) {
addParameter(key, (String) value); addParameter(key, str);
} }
else if (value instanceof String[]) { else if (value instanceof String[] strings) {
addParameter(key, (String[]) value); addParameter(key, strings);
} }
else { else {
throw new IllegalArgumentException("Parameter map value must be single value " + throw new IllegalArgumentException("Parameter map value must be single value " +
@ -1083,8 +1083,8 @@ public class MockHttpServletRequest implements HttpServletRequest {
header = new HeaderValueHolder(); header = new HeaderValueHolder();
this.headers.put(name, header); this.headers.put(name, header);
} }
if (value instanceof Collection) { if (value instanceof Collection<?> collection) {
header.addValues((Collection<?>) value); header.addValues(collection);
} }
else if (value.getClass().isArray()) { else if (value.getClass().isArray()) {
header.addValueArray(value); header.addValueArray(value);
@ -1119,14 +1119,14 @@ public class MockHttpServletRequest implements HttpServletRequest {
public long getDateHeader(String name) { public long getDateHeader(String name) {
HeaderValueHolder header = this.headers.get(name); HeaderValueHolder header = this.headers.get(name);
Object value = (header != null ? header.getValue() : null); Object value = (header != null ? header.getValue() : null);
if (value instanceof Date) { if (value instanceof Date date) {
return ((Date) value).getTime(); return date.getTime();
} }
else if (value instanceof Number) { else if (value instanceof Number number) {
return ((Number) value).longValue(); return number.longValue();
} }
else if (value instanceof String) { else if (value instanceof String str) {
return parseDateHeader(name, (String) value); return parseDateHeader(name, str);
} }
else if (value != null) { else if (value != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -1173,11 +1173,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
public int getIntHeader(String name) { public int getIntHeader(String name) {
HeaderValueHolder header = this.headers.get(name); HeaderValueHolder header = this.headers.get(name);
Object value = (header != null ? header.getValue() : null); Object value = (header != null ? header.getValue() : null);
if (value instanceof Number) { if (value instanceof Number number) {
return ((Number) value).intValue(); return number.intValue();
} }
else if (value instanceof String) { else if (value instanceof String str) {
return Integer.parseInt((String) value); return Integer.parseInt(str);
} }
else if (value != null) { else if (value != null) {
throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value); throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value);
@ -1248,8 +1248,9 @@ public class MockHttpServletRequest implements HttpServletRequest {
@Override @Override
public boolean isUserInRole(String role) { public boolean isUserInRole(String role) {
return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && return (this.userRoles.contains(role) ||
((MockServletContext) this.servletContext).getDeclaredRoles().contains(role))); (this.servletContext instanceof MockServletContext mockContext &&
mockContext.getDeclaredRoles().contains(role)));
} }
public void setUserPrincipal(@Nullable Principal userPrincipal) { public void setUserPrincipal(@Nullable Principal userPrincipal) {
@ -1321,7 +1322,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
public HttpSession getSession(boolean create) { public HttpSession getSession(boolean create) {
checkActive(); checkActive();
// Reset session if invalidated. // Reset session if invalidated.
if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) { if (this.session instanceof MockHttpSession mockSession && mockSession.isInvalid()) {
this.session = null; this.session = null;
} }
// Create new session if necessary. // Create new session if necessary.
@ -1346,8 +1347,8 @@ public class MockHttpServletRequest implements HttpServletRequest {
@Override @Override
public String changeSessionId() { public String changeSessionId() {
Assert.isTrue(this.session != null, "The request does not have a session"); Assert.isTrue(this.session != null, "The request does not have a session");
if (this.session instanceof MockHttpSession) { if (this.session instanceof MockHttpSession mockSession) {
return ((MockHttpSession) this.session).changeSessionId(); return mockSession.changeSessionId();
} }
return this.session.getId(); return this.session.getId();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -187,7 +187,7 @@ public abstract class ProfileValueUtils {
String environmentValue = profileValueSource.get(ifProfileValue.name()); String environmentValue = profileValueSource.get(ifProfileValue.name());
String[] annotatedValues = ifProfileValue.values(); String[] annotatedValues = ifProfileValue.values();
if (StringUtils.hasLength(ifProfileValue.value())) { if (StringUtils.hasLength(ifProfileValue.value())) {
Assert.isTrue(annotatedValues.length == 0, () -> "Setting both the 'value' and 'values' attributes " + Assert.isTrue(annotatedValues.length == 0, "Setting both the 'value' and 'values' attributes " +
"of @IfProfileValue is not allowed: choose one or the other."); "of @IfProfileValue is not allowed: choose one or the other.");
annotatedValues = new String[] { ifProfileValue.value() }; annotatedValues = new String[] { ifProfileValue.value() };
} }

View File

@ -89,10 +89,8 @@ class WiretapConnector implements ClientHttpConnector {
*/ */
ExchangeResult getExchangeResult(String requestId, @Nullable String uriTemplate, Duration timeout) { ExchangeResult getExchangeResult(String requestId, @Nullable String uriTemplate, Duration timeout) {
ClientExchangeInfo clientInfo = this.exchanges.remove(requestId); ClientExchangeInfo clientInfo = this.exchanges.remove(requestId);
Assert.state(clientInfo != null, () -> { Assert.state(clientInfo != null, () -> "No match for %s=%s".formatted(
String header = WebTestClient.WEBTESTCLIENT_REQUEST_ID; WebTestClient.WEBTESTCLIENT_REQUEST_ID, requestId));
return "No match for " + header + "=" + requestId;
});
return new ExchangeResult(clientInfo.getRequest(), clientInfo.getResponse(), return new ExchangeResult(clientInfo.getRequest(), clientInfo.getResponse(),
clientInfo.getRequest().getRecorder().getContent(), clientInfo.getRequest().getRecorder().getContent(),
clientInfo.getResponse().getRecorder().getContent(), clientInfo.getResponse().getRecorder().getContent(),

View File

@ -154,7 +154,7 @@ public class DefaultPartHttpMessageReader extends LoggingCodecSupport implements
* @see Schedulers#newBoundedElastic * @see Schedulers#newBoundedElastic
*/ */
public void setBlockingOperationScheduler(Scheduler blockingOperationScheduler) { public void setBlockingOperationScheduler(Scheduler blockingOperationScheduler) {
Assert.notNull(blockingOperationScheduler, "FileCreationScheduler must not be null"); Assert.notNull(blockingOperationScheduler, "'blockingOperationScheduler' must not be null");
this.blockingOperationScheduler = blockingOperationScheduler; this.blockingOperationScheduler = blockingOperationScheduler;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -72,7 +72,7 @@ public class ServletServerHttpResponse implements ServerHttpResponse {
@Override @Override
public void setStatusCode(HttpStatusCode status) { public void setStatusCode(HttpStatusCode status) {
Assert.notNull(status, "HttpStatus must not be null"); Assert.notNull(status, "HttpStatusCode must not be null");
this.servletResponse.setStatus(status.value()); this.servletResponse.setStatus(status.value());
} }

View File

@ -549,11 +549,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
public void setParameters(Map<String, ?> params) { public void setParameters(Map<String, ?> params) {
Assert.notNull(params, "Parameter map must not be null"); Assert.notNull(params, "Parameter map must not be null");
params.forEach((key, value) -> { params.forEach((key, value) -> {
if (value instanceof String) { if (value instanceof String str) {
setParameter(key, (String) value); setParameter(key, str);
} }
else if (value instanceof String[]) { else if (value instanceof String[] strings) {
setParameter(key, (String[]) value); setParameter(key, strings);
} }
else { else {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -598,11 +598,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
public void addParameters(Map<String, ?> params) { public void addParameters(Map<String, ?> params) {
Assert.notNull(params, "Parameter map must not be null"); Assert.notNull(params, "Parameter map must not be null");
params.forEach((key, value) -> { params.forEach((key, value) -> {
if (value instanceof String) { if (value instanceof String str) {
addParameter(key, (String) value); addParameter(key, str);
} }
else if (value instanceof String[]) { else if (value instanceof String[] strings) {
addParameter(key, (String[]) value); addParameter(key, strings);
} }
else { else {
throw new IllegalArgumentException("Parameter map value must be single value " + throw new IllegalArgumentException("Parameter map value must be single value " +
@ -1083,8 +1083,8 @@ public class MockHttpServletRequest implements HttpServletRequest {
header = new HeaderValueHolder(); header = new HeaderValueHolder();
this.headers.put(name, header); this.headers.put(name, header);
} }
if (value instanceof Collection) { if (value instanceof Collection<?> collection) {
header.addValues((Collection<?>) value); header.addValues(collection);
} }
else if (value.getClass().isArray()) { else if (value.getClass().isArray()) {
header.addValueArray(value); header.addValueArray(value);
@ -1119,14 +1119,14 @@ public class MockHttpServletRequest implements HttpServletRequest {
public long getDateHeader(String name) { public long getDateHeader(String name) {
HeaderValueHolder header = this.headers.get(name); HeaderValueHolder header = this.headers.get(name);
Object value = (header != null ? header.getValue() : null); Object value = (header != null ? header.getValue() : null);
if (value instanceof Date) { if (value instanceof Date date) {
return ((Date) value).getTime(); return date.getTime();
} }
else if (value instanceof Number) { else if (value instanceof Number number) {
return ((Number) value).longValue(); return number.longValue();
} }
else if (value instanceof String) { else if (value instanceof String str) {
return parseDateHeader(name, (String) value); return parseDateHeader(name, str);
} }
else if (value != null) { else if (value != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -1173,11 +1173,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
public int getIntHeader(String name) { public int getIntHeader(String name) {
HeaderValueHolder header = this.headers.get(name); HeaderValueHolder header = this.headers.get(name);
Object value = (header != null ? header.getValue() : null); Object value = (header != null ? header.getValue() : null);
if (value instanceof Number) { if (value instanceof Number number) {
return ((Number) value).intValue(); return number.intValue();
} }
else if (value instanceof String) { else if (value instanceof String str) {
return Integer.parseInt((String) value); return Integer.parseInt(str);
} }
else if (value != null) { else if (value != null) {
throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value); throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value);
@ -1248,8 +1248,9 @@ public class MockHttpServletRequest implements HttpServletRequest {
@Override @Override
public boolean isUserInRole(String role) { public boolean isUserInRole(String role) {
return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && return (this.userRoles.contains(role) ||
((MockServletContext) this.servletContext).getDeclaredRoles().contains(role))); (this.servletContext instanceof MockServletContext mockContext &&
mockContext.getDeclaredRoles().contains(role)));
} }
public void setUserPrincipal(@Nullable Principal userPrincipal) { public void setUserPrincipal(@Nullable Principal userPrincipal) {
@ -1321,7 +1322,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
public HttpSession getSession(boolean create) { public HttpSession getSession(boolean create) {
checkActive(); checkActive();
// Reset session if invalidated. // Reset session if invalidated.
if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) { if (this.session instanceof MockHttpSession mockSession && mockSession.isInvalid()) {
this.session = null; this.session = null;
} }
// Create new session if necessary. // Create new session if necessary.
@ -1346,8 +1347,8 @@ public class MockHttpServletRequest implements HttpServletRequest {
@Override @Override
public String changeSessionId() { public String changeSessionId() {
Assert.isTrue(this.session != null, "The request does not have a session"); Assert.isTrue(this.session != null, "The request does not have a session");
if (this.session instanceof MockHttpSession) { if (this.session instanceof MockHttpSession mockSession) {
return ((MockHttpSession) this.session).changeSessionId(); return mockSession.changeSessionId();
} }
return this.session.getId(); return this.session.getId();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -92,7 +92,8 @@ public abstract class BodyInserters {
*/ */
public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromValue(T body) { public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromValue(T body) {
Assert.notNull(body, "'body' must not be null"); Assert.notNull(body, "'body' must not be null");
Assert.isNull(registry.getAdapter(body.getClass()), "'body' should be an object, for reactive types use a variant specifying a publisher/producer and its related element type"); Assert.isNull(registry.getAdapter(body.getClass()),
"'body' should be an object, for reactive types use a variant specifying a publisher/producer and its related element type");
return (message, context) -> return (message, context) ->
writeWithMessageWriters(message, context, Mono.just(body), ResolvableType.forInstance(body), null); writeWithMessageWriters(message, context, Mono.just(body), ResolvableType.forInstance(body), null);
} }

View File

@ -113,7 +113,7 @@ final class DefaultClientResponseBuilder implements ClientResponse.Builder {
@Override @Override
public DefaultClientResponseBuilder statusCode(HttpStatusCode statusCode) { public DefaultClientResponseBuilder statusCode(HttpStatusCode statusCode) {
Assert.notNull(statusCode, "StatusCode must not be null"); Assert.notNull(statusCode, "HttpStatusCode must not be null");
this.statusCode = statusCode; this.statusCode = statusCode;
return this; return this;
} }