Polishing

This commit is contained in:
Juergen Hoeller 2024-03-04 22:48:52 +01:00
parent 24759a75f4
commit e9110c0729
21 changed files with 97 additions and 124 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -29,12 +29,10 @@ import org.springframework.core.MethodClassKey;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
/** /**
* Abstract implementation of {@link JCacheOperationSource} that caches attributes * Abstract implementation of {@link JCacheOperationSource} that caches operations
* for methods and implements a fallback policy: 1. specific target method; * for methods and implements a fallback policy: 1. specific target method;
* 2. declaring method. * 2. declaring method.
* *
* <p>This implementation caches attributes by method after they are first used.
*
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 4.1 * @since 4.1
@ -43,24 +41,25 @@ import org.springframework.lang.Nullable;
public abstract class AbstractFallbackJCacheOperationSource implements JCacheOperationSource { public abstract class AbstractFallbackJCacheOperationSource implements JCacheOperationSource {
/** /**
* Canonical value held in cache to indicate no caching attribute was * Canonical value held in cache to indicate no cache operation was
* found for this method and we don't need to look again. * found for this method, and we don't need to look again.
*/ */
private static final Object NULL_CACHING_ATTRIBUTE = new Object(); private static final Object NULL_CACHING_MARKER = new Object();
protected final Log logger = LogFactory.getLog(getClass()); protected final Log logger = LogFactory.getLog(getClass());
private final Map<MethodClassKey, Object> cache = new ConcurrentHashMap<>(1024); private final Map<MethodClassKey, Object> operationCache = new ConcurrentHashMap<>(1024);
@Override @Override
@Nullable
public JCacheOperation<?> getCacheOperation(Method method, @Nullable Class<?> targetClass) { public JCacheOperation<?> getCacheOperation(Method method, @Nullable Class<?> targetClass) {
MethodClassKey cacheKey = new MethodClassKey(method, targetClass); MethodClassKey cacheKey = new MethodClassKey(method, targetClass);
Object cached = this.cache.get(cacheKey); Object cached = this.operationCache.get(cacheKey);
if (cached != null) { if (cached != null) {
return (cached != NULL_CACHING_ATTRIBUTE ? (JCacheOperation<?>) cached : null); return (cached != NULL_CACHING_MARKER ? (JCacheOperation<?>) cached : null);
} }
else { else {
JCacheOperation<?> operation = computeCacheOperation(method, targetClass); JCacheOperation<?> operation = computeCacheOperation(method, targetClass);
@ -68,10 +67,10 @@ public abstract class AbstractFallbackJCacheOperationSource implements JCacheOpe
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Adding cacheable method '" + method.getName() + "' with operation: " + operation); logger.debug("Adding cacheable method '" + method.getName() + "' with operation: " + operation);
} }
this.cache.put(cacheKey, operation); this.operationCache.put(cacheKey, operation);
} }
else { else {
this.cache.put(cacheKey, NULL_CACHING_ATTRIBUTE); this.operationCache.put(cacheKey, NULL_CACHING_MARKER);
} }
return operation; return operation;
} }
@ -84,7 +83,7 @@ public abstract class AbstractFallbackJCacheOperationSource implements JCacheOpe
return null; return null;
} }
// The method may be on an interface, but we need attributes from the target class. // The method may be on an interface, but we need metadata from the target class.
// If the target class is null, the method will be unchanged. // If the target class is null, the method will be unchanged.
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2024 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.
@ -212,10 +212,8 @@ public abstract class AnnotationJCacheOperationSource extends AbstractFallbackJC
for (Class<?> parameterType : parameterTypes) { for (Class<?> parameterType : parameterTypes) {
parameters.add(parameterType.getName()); parameters.add(parameterType.getName());
} }
return method.getDeclaringClass().getName() + '.' + method.getName() +
return method.getDeclaringClass().getName() '(' + StringUtils.collectionToCommaDelimitedString(parameters) + ')';
+ '.' + method.getName()
+ '(' + StringUtils.collectionToCommaDelimitedString(parameters) + ')';
} }
private int countNonNull(Object... instances) { private int countNonNull(Object... instances) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -46,6 +46,7 @@ public class BeanFactoryJCacheOperationSourceAdvisor extends AbstractBeanFactory
* Set the cache operation attribute source which is used to find cache * Set the cache operation attribute source which is used to find cache
* attributes. This should usually be identical to the source reference * attributes. This should usually be identical to the source reference
* set on the cache interceptor itself. * set on the cache interceptor itself.
* @see JCacheInterceptor#setCacheOperationSource
*/ */
public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) { public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) {
this.pointcut.setCacheOperationSource(cacheOperationSource); this.pointcut.setCacheOperationSource(cacheOperationSource);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2024 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.
@ -34,7 +34,7 @@ public interface JCacheOperationSource {
* Return the cache operations for this method, or {@code null} * Return the cache operations for this method, or {@code null}
* if the method contains no <em>JSR-107</em> related metadata. * if the method contains no <em>JSR-107</em> related metadata.
* @param method the method to introspect * @param method the method to introspect
* @param targetClass the target class (may be {@code null}, in which case * @param targetClass the target class (can be {@code null}, in which case
* the declaring class of the method must be used) * the declaring class of the method must be used)
* @return the cache operation for this method, or {@code null} if none found * @return the cache operation for this method, or {@code null} if none found
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 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.
@ -24,7 +24,7 @@ import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
/** /**
* A Pointcut that matches if the underlying {@link JCacheOperationSource} * A {@code Pointcut} that matches if the underlying {@link JCacheOperationSource}
* has an operation for a given method. * has an operation for a given method.
* *
* @author Stephane Nicoll * @author Stephane Nicoll

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,20 +32,16 @@ import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
/** /**
* Abstract implementation of {@link CacheOperation} that caches attributes * Abstract implementation of {@link CacheOperationSource} that caches operations
* for methods and implements a fallback policy: 1. specific target method; * for methods and implements a fallback policy: 1. specific target method;
* 2. target class; 3. declaring method; 4. declaring class/interface. * 2. target class; 3. declaring method; 4. declaring class/interface.
* *
* <p>Defaults to using the target class's caching attribute if none is * <p>Defaults to using the target class's declared cache operations if none are
* associated with the target method. Any caching attribute associated with * associated with the target method. Any cache operations associated with
* the target method completely overrides a class caching attribute. * the target method completely override any class-level declarations.
* If none found on the target class, the interface that the invoked method * If none found on the target class, the interface that the invoked method
* has been called through (in case of a JDK proxy) will be checked. * has been called through (in case of a JDK proxy) will be checked.
* *
* <p>This implementation caches attributes by method after they are first
* used. If it is ever desirable to allow dynamic changing of cacheable
* attributes (which is very unlikely), caching could be made configurable.
*
* @author Costin Leau * @author Costin Leau
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 3.1 * @since 3.1
@ -53,10 +49,10 @@ import org.springframework.util.ClassUtils;
public abstract class AbstractFallbackCacheOperationSource implements CacheOperationSource { public abstract class AbstractFallbackCacheOperationSource implements CacheOperationSource {
/** /**
* Canonical value held in cache to indicate no caching attribute was * Canonical value held in cache to indicate no cache operation was
* found for this method and we don't need to look again. * found for this method, and we don't need to look again.
*/ */
private static final Collection<CacheOperation> NULL_CACHING_ATTRIBUTE = Collections.emptyList(); private static final Collection<CacheOperation> NULL_CACHING_MARKER = Collections.emptyList();
/** /**
@ -71,14 +67,14 @@ public abstract class AbstractFallbackCacheOperationSource implements CacheOpera
* <p>As this base class is not marked Serializable, the cache will be recreated * <p>As this base class is not marked Serializable, the cache will be recreated
* after serialization - provided that the concrete subclass is Serializable. * after serialization - provided that the concrete subclass is Serializable.
*/ */
private final Map<Object, Collection<CacheOperation>> attributeCache = new ConcurrentHashMap<>(1024); private final Map<Object, Collection<CacheOperation>> operationCache = new ConcurrentHashMap<>(1024);
/** /**
* Determine the caching attribute for this method invocation. * Determine the cache operations for this method invocation.
* <p>Defaults to the class's caching attribute if no method attribute is found. * <p>Defaults to class-declared metadata if no method-level metadata is found.
* @param method the method for the current invocation (never {@code null}) * @param method the method for the current invocation (never {@code null})
* @param targetClass the target class for this invocation (may be {@code null}) * @param targetClass the target class for this invocation (can be {@code null})
* @return {@link CacheOperation} for this method, or {@code null} if the method * @return {@link CacheOperation} for this method, or {@code null} if the method
* is not cacheable * is not cacheable
*/ */
@ -90,21 +86,21 @@ public abstract class AbstractFallbackCacheOperationSource implements CacheOpera
} }
Object cacheKey = getCacheKey(method, targetClass); Object cacheKey = getCacheKey(method, targetClass);
Collection<CacheOperation> cached = this.attributeCache.get(cacheKey); Collection<CacheOperation> cached = this.operationCache.get(cacheKey);
if (cached != null) { if (cached != null) {
return (cached != NULL_CACHING_ATTRIBUTE ? cached : null); return (cached != NULL_CACHING_MARKER ? cached : null);
} }
else { else {
Collection<CacheOperation> cacheOps = computeCacheOperations(method, targetClass); Collection<CacheOperation> cacheOps = computeCacheOperations(method, targetClass);
if (cacheOps != null) { if (cacheOps != null) {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Adding cacheable method '" + method.getName() + "' with attribute: " + cacheOps); logger.trace("Adding cacheable method '" + method.getName() + "' with operations: " + cacheOps);
} }
this.attributeCache.put(cacheKey, cacheOps); this.operationCache.put(cacheKey, cacheOps);
} }
else { else {
this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE); this.operationCache.put(cacheKey, NULL_CACHING_MARKER);
} }
return cacheOps; return cacheOps;
} }
@ -129,7 +125,7 @@ public abstract class AbstractFallbackCacheOperationSource implements CacheOpera
return null; return null;
} }
// The method may be on an interface, but we need attributes from the target class. // The method may be on an interface, but we need metadata from the target class.
// If the target class is null, the method will be unchanged. // If the target class is null, the method will be unchanged.
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
@ -163,19 +159,19 @@ public abstract class AbstractFallbackCacheOperationSource implements CacheOpera
/** /**
* Subclasses need to implement this to return the caching attribute for the * Subclasses need to implement this to return the cache operations for the
* given class, if any. * given class, if any.
* @param clazz the class to retrieve the attribute for * @param clazz the class to retrieve the cache operations for
* @return all caching attribute associated with this class, or {@code null} if none * @return all cache operations associated with this class, or {@code null} if none
*/ */
@Nullable @Nullable
protected abstract Collection<CacheOperation> findCacheOperations(Class<?> clazz); protected abstract Collection<CacheOperation> findCacheOperations(Class<?> clazz);
/** /**
* Subclasses need to implement this to return the caching attribute for the * Subclasses need to implement this to return the cache operations for the
* given method, if any. * given method, if any.
* @param method the method to retrieve the attribute for * @param method the method to retrieve the cache operations for
* @return all caching attribute associated with this method, or {@code null} if none * @return all cache operations associated with this method, or {@code null} if none
*/ */
@Nullable @Nullable
protected abstract Collection<CacheOperation> findCacheOperations(Method method); protected abstract Collection<CacheOperation> findCacheOperations(Method method);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -54,7 +54,7 @@ public interface CacheOperationSource {
* Return the collection of cache operations for this method, * Return the collection of cache operations for this method,
* or {@code null} if the method contains no <em>cacheable</em> annotations. * or {@code null} if the method contains no <em>cacheable</em> annotations.
* @param method the method to introspect * @param method the method to introspect
* @param targetClass the target class (may be {@code null}, in which case * @param targetClass the target class (can be {@code null}, in which case
* the declaring class of the method must be used) * the declaring class of the method must be used)
* @return all cache operations for this method, or {@code null} if none found * @return all cache operations for this method, or {@code null} if none found
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 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.
@ -28,7 +28,7 @@ import org.springframework.util.ObjectUtils;
/** /**
* A {@code Pointcut} that matches if the underlying {@link CacheOperationSource} * A {@code Pointcut} that matches if the underlying {@link CacheOperationSource}
* has an attribute for a given method. * has an operation for a given method.
* *
* @author Costin Leau * @author Costin Leau
* @author Juergen Hoeller * @author Juergen Hoeller
@ -36,7 +36,7 @@ import org.springframework.util.ObjectUtils;
* @since 3.1 * @since 3.1
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implements Serializable { final class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
@Nullable @Nullable
private CacheOperationSource cacheOperationSource; private CacheOperationSource cacheOperationSource;
@ -78,7 +78,7 @@ class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implement
* {@link ClassFilter} that delegates to {@link CacheOperationSource#isCandidateClass} * {@link ClassFilter} that delegates to {@link CacheOperationSource#isCandidateClass}
* for filtering classes whose methods are not worth searching to begin with. * for filtering classes whose methods are not worth searching to begin with.
*/ */
private class CacheOperationSourceClassFilter implements ClassFilter { private final class CacheOperationSourceClassFilter implements ClassFilter {
@Override @Override
public boolean matches(Class<?> clazz) { public boolean matches(Class<?> clazz) {
@ -88,6 +88,7 @@ class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implement
return (cacheOperationSource == null || cacheOperationSource.isCandidateClass(clazz)); return (cacheOperationSource == null || cacheOperationSource.isCandidateClass(clazz));
} }
@Nullable
private CacheOperationSource getCacheOperationSource() { private CacheOperationSource getCacheOperationSource() {
return cacheOperationSource; return cacheOperationSource;
} }
@ -95,7 +96,7 @@ class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implement
@Override @Override
public boolean equals(@Nullable Object other) { public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof CacheOperationSourceClassFilter that && return (this == other || (other instanceof CacheOperationSourceClassFilter that &&
ObjectUtils.nullSafeEquals(cacheOperationSource, that.getCacheOperationSource()))); ObjectUtils.nullSafeEquals(getCacheOperationSource(), that.getCacheOperationSource())));
} }
@Override @Override
@ -105,9 +106,8 @@ class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implement
@Override @Override
public String toString() { public String toString() {
return CacheOperationSourceClassFilter.class.getName() + ": " + cacheOperationSource; return CacheOperationSourceClassFilter.class.getName() + ": " + getCacheOperationSource();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 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.
@ -98,8 +98,8 @@ public class AsyncAnnotationBeanPostProcessor extends AbstractBeanFactoryAwareAd
* applying the corresponding default if a supplier is not resolvable. * applying the corresponding default if a supplier is not resolvable.
* @since 5.1 * @since 5.1
*/ */
public void configure( public void configure(@Nullable Supplier<Executor> executor,
@Nullable Supplier<Executor> executor, @Nullable Supplier<AsyncUncaughtExceptionHandler> exceptionHandler) { @Nullable Supplier<AsyncUncaughtExceptionHandler> exceptionHandler) {
this.executor = executor; this.executor = executor;
this.exceptionHandler = exceptionHandler; this.exceptionHandler = exceptionHandler;

View File

@ -38,7 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
class DataBinderConstructTests { class DataBinderConstructTests {
@Test @Test
void dataClassBinding() { void dataClassBinding() {
MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1", "param2", "true")); MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1", "param2", "true"));
@ -78,7 +77,7 @@ class DataBinderConstructTests {
assertThat(bindingResult.getFieldValue("param3")).isNull(); assertThat(bindingResult.getFieldValue("param3")).isNull();
} }
@Test // gh-31821 @Test // gh-31821
void dataClassBindingWithNestedOptionalParameterWithMissingParameter() { void dataClassBindingWithNestedOptionalParameterWithMissingParameter() {
MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1")); MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1"));
DataBinder binder = initDataBinder(NestedDataClass.class); DataBinder binder = initDataBinder(NestedDataClass.class);

View File

@ -2055,7 +2055,7 @@ class DataBinderTests {
.withMessageContaining("DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); .withMessageContaining("DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods");
} }
@Test // SPR-15009 @Test // SPR-15009
void setCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() { void setCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() {
TestBean testBean = new TestBean(); TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean"); DataBinder binder = new DataBinder(testBean, "testBean");
@ -2072,7 +2072,7 @@ class DataBinderTests {
assertThat(((BeanWrapper) binder.getInternalBindingResult().getPropertyAccessor()).getAutoGrowCollectionLimit()).isEqualTo(512); assertThat(((BeanWrapper) binder.getInternalBindingResult().getPropertyAccessor()).getAutoGrowCollectionLimit()).isEqualTo(512);
} }
@Test // SPR-15009 @Test // SPR-15009
void setCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() { void setCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() {
TestBean testBean = new TestBean(); TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean"); DataBinder binder = new DataBinder(testBean, "testBean");
@ -2126,7 +2126,7 @@ class DataBinderTests {
.withMessageContaining("DataBinder is already initialized with MessageCodesResolver"); .withMessageContaining("DataBinder is already initialized with MessageCodesResolver");
} }
@Test // gh-24347 @Test // gh-24347
void overrideBindingResultType() { void overrideBindingResultType() {
TestBean testBean = new TestBean(); TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean"); DataBinder binder = new DataBinder(testBean, "testBean");

View File

@ -83,8 +83,7 @@ class MethodValidationProxyTests {
context.close(); context.close();
} }
@Test // gh-29782 @Test // gh-29782
@SuppressWarnings("unchecked")
public void testMethodValidationPostProcessorForInterfaceOnlyProxy() { public void testMethodValidationPostProcessorForInterfaceOnlyProxy() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(MethodValidationPostProcessor.class); context.register(MethodValidationPostProcessor.class);

View File

@ -658,7 +658,7 @@ public class ResolvableType implements Serializable {
* @param nestingLevel the required nesting level, indexed from 1 for the * @param nestingLevel the required nesting level, indexed from 1 for the
* current type, 2 for the first nested generic, 3 for the second and so on * current type, 2 for the first nested generic, 3 for the second and so on
* @param typeIndexesPerLevel a map containing the generic index for a given * @param typeIndexesPerLevel a map containing the generic index for a given
* nesting level (may be {@code null}) * nesting level (can be {@code null})
* @return a {@code ResolvableType} for the nested level, or {@link #NONE} * @return a {@code ResolvableType} for the nested level, or {@link #NONE}
*/ */
public ResolvableType getNested(int nestingLevel, @Nullable Map<Integer, Integer> typeIndexesPerLevel) { public ResolvableType getNested(int nestingLevel, @Nullable Map<Integer, Integer> typeIndexesPerLevel) {
@ -690,7 +690,7 @@ public class ResolvableType implements Serializable {
* generic is returned. * generic is returned.
* <p>If no generic is available at the specified indexes {@link #NONE} is returned. * <p>If no generic is available at the specified indexes {@link #NONE} is returned.
* @param indexes the indexes that refer to the generic parameter * @param indexes the indexes that refer to the generic parameter
* (may be omitted to return the first generic) * (can be omitted to return the first generic)
* @return a {@code ResolvableType} for the specified generic, or {@link #NONE} * @return a {@code ResolvableType} for the specified generic, or {@link #NONE}
* @see #hasGenerics() * @see #hasGenerics()
* @see #getGenerics() * @see #getGenerics()
@ -793,7 +793,7 @@ public class ResolvableType implements Serializable {
* Convenience method that will {@link #getGeneric(int...) get} and * Convenience method that will {@link #getGeneric(int...) get} and
* {@link #resolve() resolve} a specific generic parameter. * {@link #resolve() resolve} a specific generic parameter.
* @param indexes the indexes that refer to the generic parameter * @param indexes the indexes that refer to the generic parameter
* (may be omitted to return the first generic) * (can be omitted to return the first generic)
* @return a resolved {@link Class} or {@code null} * @return a resolved {@link Class} or {@code null}
* @see #getGeneric(int...) * @see #getGeneric(int...)
* @see #resolve() * @see #resolve()

View File

@ -31,7 +31,6 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* Integration tests for {@link MockMvcWebConnection}. * Integration tests for {@link MockMvcWebConnection}.
* *
@ -64,14 +63,15 @@ public class MockMvcWebConnectionTests {
public void contextPathEmpty() { public void contextPathEmpty() {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, "")); this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, ""));
// Empty context path (root context) should not match to a URL with a context path // Empty context path (root context) should not match to a URL with a context path
assertThatExceptionOfType(FailingHttpStatusCodeException.class).isThrownBy(() -> assertThatExceptionOfType(FailingHttpStatusCodeException.class)
this.webClient.getPage("http://localhost/context/a")) .isThrownBy(() -> this.webClient.getPage("http://localhost/context/a"))
.satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404)); .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404));
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient)); this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient));
// No context is the same providing an empty context path // No context is the same providing an empty context path
assertThatExceptionOfType(FailingHttpStatusCodeException.class).isThrownBy(() -> assertThatExceptionOfType(FailingHttpStatusCodeException.class)
this.webClient.getPage("http://localhost/context/a")) .isThrownBy(() -> this.webClient.getPage("http://localhost/context/a"))
.satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404)); .satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(404));
} }
@Test @Test
@ -84,8 +84,9 @@ public class MockMvcWebConnectionTests {
@Test @Test
public void infiniteForward() { public void infiniteForward() {
this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, "")); this.webClient.setWebConnection(new MockMvcWebConnection(this.mockMvc, this.webClient, ""));
assertThatIllegalStateException().isThrownBy(() -> this.webClient.getPage("http://localhost/infiniteForward")) assertThatIllegalStateException()
.withMessage("Forwarded 100 times in a row, potential infinite forward loop"); .isThrownBy(() -> this.webClient.getPage("http://localhost/infiniteForward"))
.withMessage("Forwarded 100 times in a row, potential infinite forward loop");
} }
@Test @Test

View File

@ -32,7 +32,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests for {@link MockWebResponseBuilder}. * Tests for {@link MockWebResponseBuilder}.
* *
@ -55,8 +54,6 @@ public class MockWebResponseBuilderTests {
} }
// --- constructor
@Test @Test
public void constructorWithNullWebRequest() { public void constructorWithNullWebRequest() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
@ -66,12 +63,10 @@ public class MockWebResponseBuilderTests {
@Test @Test
public void constructorWithNullResponse() { public void constructorWithNullResponse() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
new MockWebResponseBuilder(0L, new WebRequest(new URL("http://company.example:80/test/this/here")), null)); new MockWebResponseBuilder(0L,
new WebRequest(new URL("http://company.example:80/test/this/here")), null));
} }
// --- build
@Test @Test
public void buildContent() throws Exception { public void buildContent() throws Exception {
this.response.getWriter().write("expected content"); this.response.getWriter().write("expected content");
@ -124,8 +119,7 @@ public class MockWebResponseBuilderTests {
.endsWith("; Secure; HttpOnly"); .endsWith("; Secure; HttpOnly");
} }
// SPR-14169 @Test // SPR-14169
@Test
public void buildResponseHeadersNullDomainDefaulted() throws Exception { public void buildResponseHeadersNullDomainDefaulted() throws Exception {
Cookie cookie = new Cookie("cookieA", "valueA"); Cookie cookie = new Cookie("cookieA", "valueA");
this.response.addCookie(cookie); this.response.addCookie(cookie);

View File

@ -50,6 +50,7 @@ class MockMvcHtmlUnitDriverBuilderTests {
private HtmlUnitDriver driver; private HtmlUnitDriver driver;
MockMvcHtmlUnitDriverBuilderTests(WebApplicationContext wac) { MockMvcHtmlUnitDriverBuilderTests(WebApplicationContext wac) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
} }

View File

@ -48,6 +48,7 @@ class WebConnectionHtmlUnitDriverTests {
@Mock @Mock
private WebConnection connection; private WebConnection connection;
@BeforeEach @BeforeEach
void setup() throws Exception { void setup() throws Exception {
given(this.connection.getResponse(any(WebRequest.class))).willThrow(new IOException("")); given(this.connection.getResponse(any(WebRequest.class))).willThrow(new IOException(""));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,11 +42,6 @@ import org.springframework.util.StringValueResolver;
* If none found on the target class, the interface that the invoked method * If none found on the target class, the interface that the invoked method
* has been called through (in case of a JDK proxy) will be checked. * has been called through (in case of a JDK proxy) will be checked.
* *
* <p>This implementation caches attributes by method after they are first used.
* If it is ever desirable to allow dynamic changing of transaction attributes
* (which is very unlikely), caching could be made configurable. Caching is
* desirable because of the cost of evaluating rollback rules.
*
* @author Rod Johnson * @author Rod Johnson
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 1.1 * @since 1.1
@ -95,7 +90,7 @@ public abstract class AbstractFallbackTransactionAttributeSource
* Determine the transaction attribute for this method invocation. * Determine the transaction attribute for this method invocation.
* <p>Defaults to the class's transaction attribute if no method attribute is found. * <p>Defaults to the class's transaction attribute if no method attribute is found.
* @param method the method for the current invocation (never {@code null}) * @param method the method for the current invocation (never {@code null})
* @param targetClass the target class for this invocation (may be {@code null}) * @param targetClass the target class for this invocation (can be {@code null})
* @return a TransactionAttribute for this method, or {@code null} if the method * @return a TransactionAttribute for this method, or {@code null} if the method
* is not transactional * is not transactional
*/ */
@ -106,27 +101,15 @@ public abstract class AbstractFallbackTransactionAttributeSource
return null; return null;
} }
// First, see if we have a cached value.
Object cacheKey = getCacheKey(method, targetClass); Object cacheKey = getCacheKey(method, targetClass);
TransactionAttribute cached = this.attributeCache.get(cacheKey); TransactionAttribute cached = this.attributeCache.get(cacheKey);
if (cached != null) { if (cached != null) {
// Value will either be canonical value indicating there is no transaction attribute, return (cached != NULL_TRANSACTION_ATTRIBUTE ? cached : null);
// or an actual transaction attribute.
if (cached == NULL_TRANSACTION_ATTRIBUTE) {
return null;
}
else {
return cached;
}
} }
else { else {
// We need to work it out.
TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass); TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
// Put it in the cache. if (txAttr != null) {
if (txAttr == null) {
this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
}
else {
String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass); String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
if (txAttr instanceof DefaultTransactionAttribute dta) { if (txAttr instanceof DefaultTransactionAttribute dta) {
dta.setDescriptor(methodIdentification); dta.setDescriptor(methodIdentification);
@ -137,6 +120,9 @@ public abstract class AbstractFallbackTransactionAttributeSource
} }
this.attributeCache.put(cacheKey, txAttr); this.attributeCache.put(cacheKey, txAttr);
} }
else {
this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
}
return txAttr; return txAttr;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 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.
@ -57,7 +57,7 @@ public interface TransactionAttributeSource {
* Return the transaction attribute for the given method, * Return the transaction attribute for the given method,
* or {@code null} if the method is non-transactional. * or {@code null} if the method is non-transactional.
* @param method the method to introspect * @param method the method to introspect
* @param targetClass the target class (may be {@code null}, * @param targetClass the target class (can be {@code null},
* in which case the declaring class of the method must be used) * in which case the declaring class of the method must be used)
* @return the matching transaction attribute, or {@code null} if none found * @return the matching transaction attribute, or {@code null} if none found
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 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.
@ -77,7 +77,7 @@ final class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointc
* {@link ClassFilter} that delegates to {@link TransactionAttributeSource#isCandidateClass} * {@link ClassFilter} that delegates to {@link TransactionAttributeSource#isCandidateClass}
* for filtering classes whose methods are not worth searching to begin with. * for filtering classes whose methods are not worth searching to begin with.
*/ */
private class TransactionAttributeSourceClassFilter implements ClassFilter { private final class TransactionAttributeSourceClassFilter implements ClassFilter {
@Override @Override
public boolean matches(Class<?> clazz) { public boolean matches(Class<?> clazz) {
@ -89,6 +89,7 @@ final class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointc
return (transactionAttributeSource == null || transactionAttributeSource.isCandidateClass(clazz)); return (transactionAttributeSource == null || transactionAttributeSource.isCandidateClass(clazz));
} }
@Nullable
private TransactionAttributeSource getTransactionAttributeSource() { private TransactionAttributeSource getTransactionAttributeSource() {
return transactionAttributeSource; return transactionAttributeSource;
} }
@ -96,7 +97,7 @@ final class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointc
@Override @Override
public boolean equals(@Nullable Object other) { public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof TransactionAttributeSourceClassFilter that && return (this == other || (other instanceof TransactionAttributeSourceClassFilter that &&
ObjectUtils.nullSafeEquals(transactionAttributeSource, that.getTransactionAttributeSource()))); ObjectUtils.nullSafeEquals(getTransactionAttributeSource(), that.getTransactionAttributeSource())));
} }
@Override @Override
@ -106,9 +107,8 @@ final class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointc
@Override @Override
public String toString() { public String toString() {
return TransactionAttributeSourceClassFilter.class.getName() + ": " + transactionAttributeSource; return TransactionAttributeSourceClassFilter.class.getName() + ": " + getTransactionAttributeSource();
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 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.
@ -218,7 +218,6 @@ public abstract class AbstractHttpMessageConverter<T> implements HttpMessageConv
public OutputStream getBody() { public OutputStream getBody() {
return outputStream; return outputStream;
} }
@Override @Override
public HttpHeaders getHeaders() { public HttpHeaders getHeaders() {
return headers; return headers;
@ -304,8 +303,7 @@ public abstract class AbstractHttpMessageConverter<T> implements HttpMessageConv
* Indicates whether this message converter can * Indicates whether this message converter can
* {@linkplain #write(Object, MediaType, HttpOutputMessage) write} the * {@linkplain #write(Object, MediaType, HttpOutputMessage) write} the
* given object multiple times. * given object multiple times.
* * <p>The default implementation returns {@code false}.
* <p>Default implementation returns {@code false}.
* @param t the object t * @param t the object t
* @return {@code true} if {@code t} can be written repeatedly; * @return {@code true} if {@code t} can be written repeatedly;
* {@code false} otherwise * {@code false} otherwise