Compare commits

..

1 Commits

Author SHA1 Message Date
Spring Builds 3540029931 Release v5.3.26 2023-03-20 09:52:18 +00:00
167 changed files with 1709 additions and 3585 deletions
+1 -3
View File
@@ -46,6 +46,4 @@ atlassian-ide-plugin.xml
.gradletasknamecache
# VS Code
.vscode/
cached-antora-playbook.yml
.vscode/
+1 -1
View File
@@ -1,3 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=8.0.372-librca
java=8.0.362-librca
+7 -7
View File
@@ -28,8 +28,8 @@ configure(allprojects) { project ->
dependencyManagement {
imports {
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.7"
mavenBom "io.netty:netty-bom:4.1.94.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.34"
mavenBom "io.netty:netty-bom:4.1.90.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.30"
mavenBom "io.r2dbc:r2dbc-bom:Arabba-SR13"
mavenBom "io.rsocket:rsocket-bom:1.1.3"
mavenBom "org.eclipse.jetty:jetty-bom:9.4.51.v20230217"
@@ -128,18 +128,18 @@ configure(allprojects) { project ->
dependency "org.webjars:webjars-locator-core:0.48"
dependency "org.webjars:underscorejs:1.8.3"
dependencySet(group: 'org.apache.tomcat', version: '9.0.78') {
dependencySet(group: 'org.apache.tomcat', version: '9.0.73') {
entry 'tomcat-util'
entry('tomcat-websocket') {
exclude group: "org.apache.tomcat", name: "tomcat-servlet-api"
exclude group: "org.apache.tomcat", name: "tomcat-websocket-api"
}
}
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.78') {
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.73') {
entry 'tomcat-embed-core'
entry 'tomcat-embed-websocket'
}
dependencySet(group: 'io.undertow', version: '2.2.25.Final') {
dependencySet(group: 'io.undertow', version: '2.2.23.Final') {
entry 'undertow-core'
entry('undertow-servlet') {
exclude group: "org.jboss.spec.javax.servlet", name: "jboss-servlet-api_4.0_spec"
@@ -238,7 +238,7 @@ configure(allprojects) { project ->
dependency "com.ibm.websphere:uow:6.0.2.17"
dependency "com.jamonapi:jamon:2.82"
dependency "joda-time:joda-time:2.10.13"
dependency "org.eclipse.persistence:org.eclipse.persistence.jpa:2.7.12"
dependency "org.eclipse.persistence:org.eclipse.persistence.jpa:2.7.10"
dependency "org.javamoney:moneta:1.3"
dependency "com.sun.activation:javax.activation:1.2.0"
@@ -340,7 +340,7 @@ configure([rootProject] + javaProjects) { project ->
}
checkstyle {
toolVersion = "10.12.1"
toolVersion = "10.9.1"
configDirectory.set(rootProject.file("src/checkstyle"))
}
+1 -1
View File
@@ -1,4 +1,4 @@
FROM ubuntu:jammy-20230624
FROM ubuntu:focal-20220922
ADD setup.sh /setup.sh
ADD get-jdk-url.sh /get-jdk-url.sh
+2 -2
View File
@@ -3,10 +3,10 @@ set -e
case "$1" in
java8)
echo "https://github.com/bell-sw/Liberica/releases/download/8u372+7/bellsoft-jdk8u372+7-linux-amd64.tar.gz"
echo "https://github.com/bell-sw/Liberica/releases/download/8u345+1/bellsoft-jdk8u345+1-linux-amd64.tar.gz"
;;
java17)
echo "https://github.com/bell-sw/Liberica/releases/download/17.0.7+7/bellsoft-jdk17.0.7+7-linux-amd64.tar.gz"
echo "https://github.com/bell-sw/Liberica/releases/download/17.0.4+8/bellsoft-jdk17.0.4+8-linux-amd64.tar.gz"
;;
*)
echo $"Unknown java version"
+47
View File
@@ -64,6 +64,12 @@ resource_types:
<<: *docker-resource-source
repository: dpb587/github-status-resource
tag: master
- name: pull-request
type: registry-image
source:
<<: *docker-resource-source
repository: teliaoss/github-pr-resource
tag: v0.23.0
- name: slack-notification
type: registry-image
source:
@@ -105,6 +111,14 @@ resources:
username: ((artifactory-username))
password: ((artifactory-password))
build_name: ((build-name))
- name: git-pull-request
type: pull-request
icon: source-pull
source:
access_token: ((github-ci-pull-request-token))
repository: ((github-repo-name))
base_branch: ((branch))
ignore_paths: ["ci/*"]
- name: repo-status-build
type: github-status-resource
icon: eye-check-outline
@@ -245,6 +259,37 @@ jobs:
<<: *slack-fail-params
- put: repo-status-jdk17-build
params: { state: "success", commit: "git-repo" }
- name: build-pull-requests
serial: true
public: true
plan:
- get: ci-image
- get: git-repo
resource: git-pull-request
trigger: true
version: every
- do:
- put: git-pull-request
params:
path: git-repo
status: pending
- task: build-pr
image: ci-image
file: git-repo/ci/tasks/build-pr.yml
privileged: true
timeout: ((task-timeout))
params:
BRANCH: ((branch))
on_success:
put: git-pull-request
params:
path: git-repo
status: success
on_failure:
put: git-pull-request
params:
path: git-repo
status: failure
- name: stage-milestone
serial: true
plan:
@@ -397,3 +442,5 @@ groups:
jobs: ["stage-milestone", "stage-rc", "stage-release", "promote-milestone", "promote-rc", "promote-release", "create-github-release"]
- name: "ci-images"
jobs: ["build-ci-images"]
- name: "pull-requests"
jobs: [ "build-pull-requests" ]
-2
View File
@@ -5,8 +5,6 @@ image_resource:
source:
repository: springio/github-changelog-generator
tag: '0.0.7'
username: ((docker-hub-username))
password: ((docker-hub-password))
inputs:
- name: git-repo
- name: artifactory-repo
-2
View File
@@ -5,8 +5,6 @@ image_resource:
source:
repository: springio/concourse-release-scripts
tag: '0.3.4'
username: ((docker-hub-username))
password: ((docker-hub-password))
inputs:
- name: git-repo
- name: artifactory-repo
+1 -1
View File
@@ -1,4 +1,4 @@
version=5.3.29
version=5.3.26
org.gradle.jvmargs=-Xmx2048m
org.gradle.caching=true
org.gradle.parallel=true
+4 -3
View File
@@ -3,7 +3,7 @@ configurations {
}
dependencies {
asciidoctorExt("io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.6.1")
asciidoctorExt("io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.5.0")
}
repositories {
@@ -73,8 +73,9 @@ pluginManager.withPlugin("kotlin") {
}
task downloadResources(type: Download) {
src "https://repo.spring.io/artifactory/snapshot/io/spring/docresources/" +
"spring-doc-resources/0.2.6-SNAPSHOT/spring-doc-resources-0.2.6-20210308.231804-2.zip"
def version = "0.2.5"
src "https://repo.spring.io/release/io/spring/docresources/" +
"spring-doc-resources/$version/spring-doc-resources-${version}.zip"
dest project.file("$buildDir/docs/spring-doc-resources.zip")
onlyIfModified true
useETag "all"
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,14 +38,6 @@ import org.springframework.util.StringUtils;
* for an advice method from the pointcut expression, returning, and throwing clauses.
* If an unambiguous interpretation is not available, it returns {@code null}.
*
* <h3>Algorithm Summary</h3>
* <p>If an unambiguous binding can be deduced, then it is.
* If the advice requirements cannot possibly be satisfied, then {@code null}
* is returned. By setting the {@link #setRaiseExceptions(boolean) raiseExceptions}
* property to {@code true}, descriptive exceptions will be thrown instead of
* returning {@code null} in the case that the parameter names cannot be discovered.
*
* <h3>Algorithm Details</h3>
* <p>This class interprets arguments in the following way:
* <ol>
* <li>If the first parameter of the method is of type {@link JoinPoint}
@@ -73,15 +65,15 @@ import org.springframework.util.StringUtils;
* zero we proceed to the next stage. If {@code a} &gt; 1 then an
* {@code AmbiguousBindingException} is raised. If {@code a} == 1,
* and there are no unbound arguments of type {@code Annotation+},
* then an {@code IllegalArgumentException} is raised. If there is
* then an {@code IllegalArgumentException} is raised. if there is
* exactly one such argument, then the corresponding parameter name is
* assigned the value from the pointcut expression.</li>
* <li>If a {@code returningName} has been set, and there are no unbound arguments
* <li>If a returningName has been set, and there are no unbound arguments
* then an {@code IllegalArgumentException} is raised. If there is
* more than one unbound argument then an
* {@code AmbiguousBindingException} is raised. If there is exactly
* one unbound argument then the corresponding parameter name is assigned
* the value of the {@code returningName}.</li>
* the value &lt;returningName&gt;.</li>
* <li>If there remain unbound arguments, then the pointcut expression is
* examined once more for {@code this}, {@code target}, and
* {@code args} pointcut expressions used in the binding form (binding
@@ -107,12 +99,20 @@ import org.springframework.util.StringUtils;
* <p>The behavior on raising an {@code IllegalArgumentException} or
* {@code AmbiguousBindingException} is configurable to allow this discoverer
* to be used as part of a chain-of-responsibility. By default the condition will
* be logged and the {@link #getParameterNames(Method)} method will simply return
* be logged and the {@code getParameterNames(..)} method will simply return
* {@code null}. If the {@link #setRaiseExceptions(boolean) raiseExceptions}
* property is set to {@code true}, the conditions will be thrown as
* {@code IllegalArgumentException} and {@code AmbiguousBindingException},
* respectively.
*
* <p>Was that perfectly clear? ;)
*
* <p>Short version: If an unambiguous binding can be deduced, then it is.
* If the advice requirements cannot possibly be satisfied, then {@code null}
* is returned. By setting the {@link #setRaiseExceptions(boolean) raiseExceptions}
* property to {@code true}, descriptive exceptions will be thrown instead of
* returning {@code null} in the case that the parameter names cannot be discovered.
*
* @author Adrian Colyer
* @author Juergen Hoeller
* @since 2.0
@@ -158,7 +158,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
/** The pointcut expression associated with the advice, as a simple String. */
@Nullable
private final String pointcutExpression;
private String pointcutExpression;
private boolean raiseExceptions;
@@ -197,7 +197,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
/**
* If {@code afterReturning} advice binds the return value, the
* {@code returning} variable name must be specified.
* returning variable name must be specified.
* @param returningName the name of the returning variable
*/
public void setReturningName(@Nullable String returningName) {
@@ -206,17 +206,18 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
/**
* If {@code afterThrowing} advice binds the thrown value, the
* {@code throwing} variable name must be specified.
* throwing variable name must be specified.
* @param throwingName the name of the throwing variable
*/
public void setThrowingName(@Nullable String throwingName) {
this.throwingName = throwingName;
}
/**
* Deduce the parameter names for an advice method.
* <p>See the {@link AspectJAdviceParameterNameDiscoverer class-level javadoc}
* for this class for details on the algorithm used.
* <p>See the {@link AspectJAdviceParameterNameDiscoverer class level javadoc}
* for this class for details of the algorithm used.
* @param method the target {@link Method}
* @return the parameter names
*/
@@ -315,13 +316,13 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
}
private void bindParameterName(int index, @Nullable String name) {
private void bindParameterName(int index, String name) {
this.parameterNameBindings[index] = name;
this.numberOfRemainingUnboundArguments--;
}
/**
* If the first parameter is of type JoinPoint or ProceedingJoinPoint, bind "thisJoinPoint" as
* If the first parameter is of type JoinPoint or ProceedingJoinPoint,bind "thisJoinPoint" as
* parameter name and return true, else return false.
*/
private boolean maybeBindThisJoinPoint() {
@@ -366,8 +367,8 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
}
if (throwableIndex == -1) {
throw new IllegalStateException("Binding of throwing parameter '" + this.throwingName +
"' could not be completed as no available arguments are a subtype of Throwable");
throw new IllegalStateException("Binding of throwing parameter '" + this.throwingName
+ "' could not be completed as no available arguments are a subtype of Throwable");
}
else {
bindParameterName(throwableIndex, this.throwingName);
@@ -399,6 +400,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
}
}
/**
* Parse the string pointcut expression looking for:
* &#64;this, &#64;target, &#64;args, &#64;within, &#64;withincode, &#64;annotation.
@@ -463,7 +465,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
}
}
/**
/*
* If the token starts meets Java identifier conventions, it's in.
*/
@Nullable
@@ -531,6 +533,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
}
}
if (varNames.size() > 1) {
throw new AmbiguousBindingException("Found " + varNames.size() +
" candidate this(), target() or args() variables but only one unbound argument slot");
@@ -606,7 +609,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
// else varNames.size must be 0 and we have nothing to bind.
}
/**
/*
* We've found the start of a binding pointcut at the given index into the
* token array. Now we need to extract the pointcut body and return it.
*/
@@ -706,7 +709,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
return false;
}
/**
/*
* Return {@code true} if the given argument type is a subclass
* of the given supertype.
*/
@@ -734,7 +737,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
return count;
}
/**
/*
* Find the argument index with the given type, and bind the given
* {@code varName} in that position.
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -521,7 +521,6 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
copy.copyFrom(this);
copy.targetSource = EmptyTargetSource.forClass(getTargetClass(), getTargetSource().isStatic());
copy.advisorChainFactory = this.advisorChainFactory;
copy.methodCache = this.methodCache;
copy.interfaces = new ArrayList<>(this.interfaces);
copy.advisors = new ArrayList<>(this.advisors);
return copy;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -283,8 +283,8 @@ class CglibAopProxy implements AopProxy, Serializable {
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
// Parameters used for optimization choices...
boolean isFrozen = this.advised.isFrozen();
boolean exposeProxy = this.advised.isExposeProxy();
boolean isFrozen = this.advised.isFrozen();
boolean isStatic = this.advised.getTargetSource().isStatic();
// Choose an "aop" interceptor (used for AOP calls).
@@ -899,9 +899,9 @@ class CglibAopProxy implements AopProxy, Serializable {
// Proxy is not yet available, but that shouldn't matter.
List<?> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
boolean haveAdvice = !chain.isEmpty();
boolean isFrozen = this.advised.isFrozen();
boolean exposeProxy = this.advised.isExposeProxy();
boolean isStatic = this.advised.getTargetSource().isStatic();
boolean isFrozen = this.advised.isFrozen();
if (haveAdvice || !isFrozen) {
// If exposing the proxy, then AOP_PROXY must be used.
if (exposeProxy) {
@@ -970,9 +970,6 @@ class CglibAopProxy implements AopProxy, Serializable {
if (this.advised.isExposeProxy() != otherAdvised.isExposeProxy()) {
return false;
}
if (this.advised.isOpaque() != otherAdvised.isOpaque()) {
return false;
}
if (this.advised.getTargetSource().isStatic() != otherAdvised.getTargetSource().isStatic()) {
return false;
}
@@ -1019,6 +1016,10 @@ class CglibAopProxy implements AopProxy, Serializable {
Advice advice = advisor.getAdvice();
hashCode = 13 * hashCode + advice.getClass().hashCode();
}
hashCode = 13 * hashCode + (this.advised.isFrozen() ? 1 : 0);
hashCode = 13 * hashCode + (this.advised.isExposeProxy() ? 1 : 0);
hashCode = 13 * hashCode + (this.advised.isOptimize() ? 1 : 0);
hashCode = 13 * hashCode + (this.advised.isOpaque() ? 1 : 0);
return hashCode;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -123,33 +123,7 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
return Proxy.newProxyInstance(determineClassLoader(classLoader), this.proxiedInterfaces, this);
}
/**
* Determine whether the JDK bootstrap or platform loader has been suggested ->
* use higher-level loader which can see Spring infrastructure classes instead.
*/
private ClassLoader determineClassLoader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
// JDK bootstrap loader -> use spring-aop ClassLoader instead.
return getClass().getClassLoader();
}
if (classLoader.getParent() == null) {
// Potentially the JDK platform loader on JDK 9+
ClassLoader aopClassLoader = getClass().getClassLoader();
ClassLoader aopParent = aopClassLoader.getParent();
while (aopParent != null) {
if (classLoader == aopParent) {
// Suggested ClassLoader is ancestor of spring-aop ClassLoader
// -> use spring-aop ClassLoader itself instead.
return aopClassLoader;
}
aopParent = aopParent.getParent();
}
}
// Regular case: use suggested ClassLoader as-is.
return classLoader;
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,6 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Convenient superclass for
@@ -82,11 +81,6 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
return this.beanFactory;
}
private ConfigurableBeanFactory getConfigurableBeanFactory() {
Assert.state(this.beanFactory != null, "BeanFactory not set");
return this.beanFactory;
}
//---------------------------------------------------------------------
// Implementation of the TargetSourceCreator interface
@@ -110,7 +104,7 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
// We need to override just this bean definition, as it may reference other beans
// and we're happy to take the parent's definition for those.
// Always use prototype scope if demanded.
BeanDefinition bd = getConfigurableBeanFactory().getMergedBeanDefinition(beanName);
BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
GenericBeanDefinition bdCopy = new GenericBeanDefinition(bd);
if (isPrototypeBased()) {
bdCopy.setScope(BeanDefinition.SCOPE_PROTOTYPE);
@@ -132,7 +126,7 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) {
synchronized (this.internalBeanFactories) {
return this.internalBeanFactories.computeIfAbsent(beanName,
name -> buildInternalBeanFactory(getConfigurableBeanFactory()));
name -> buildInternalBeanFactory(this.beanFactory));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,8 +24,6 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.aop.TargetSource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
@@ -59,18 +57,15 @@ public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSour
protected final Log logger = LogFactory.getLog(getClass());
/** Name of the target bean we will create on each invocation. */
@Nullable
private String targetBeanName;
/** Class of the target. */
@Nullable
private volatile Class<?> targetClass;
/**
* BeanFactory that owns this TargetSource. We need to hold onto this
* reference so that we can create new prototype instances as necessary.
*/
@Nullable
private BeanFactory beanFactory;
@@ -91,7 +86,6 @@ public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSour
* Return the name of the target bean in the factory.
*/
public String getTargetBeanName() {
Assert.state(this.targetBeanName != null, "Target bean name not set");
return this.targetBeanName;
}
@@ -121,13 +115,11 @@ public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSour
* Return the owning BeanFactory.
*/
public BeanFactory getBeanFactory() {
Assert.state(this.beanFactory != null, "BeanFactory not set");
return this.beanFactory;
}
@Override
@Nullable
public Class<?> getTargetClass() {
Class<?> targetClass = this.targetClass;
if (targetClass != null) {
@@ -136,7 +128,7 @@ public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSour
synchronized (this) {
// Full check within synchronization, entering the BeanFactory interaction algorithm only once...
targetClass = this.targetClass;
if (targetClass == null && this.beanFactory != null && this.targetBeanName != null) {
if (targetClass == null && this.beanFactory != null) {
// Determine type of the target bean.
targetClass = this.beanFactory.getType(this.targetBeanName);
if (targetClass == null) {
@@ -190,16 +182,18 @@ public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSour
@Override
public int hashCode() {
return getClass().hashCode() * 13 + ObjectUtils.nullSafeHashCode(this.targetBeanName);
int hashCode = getClass().hashCode();
hashCode = 13 * hashCode + ObjectUtils.nullSafeHashCode(this.beanFactory);
hashCode = 13 * hashCode + ObjectUtils.nullSafeHashCode(this.targetBeanName);
return hashCode;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getSimpleName());
sb.append(" for target bean '").append(this.targetBeanName).append('\'');
Class<?> targetClass = this.targetClass;
if (targetClass != null) {
sb.append(" of type [").append(targetClass.getName()).append(']');
if (this.targetClass != null) {
sb.append(" of type [").append(this.targetClass.getName()).append(']');
}
return sb.toString();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,7 +46,6 @@ public abstract class AbstractLazyCreationTargetSource implements TargetSource {
protected final Log logger = LogFactory.getLog(getClass());
/** The lazily initialized target object. */
@Nullable
private Object lazyTarget;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -70,7 +70,6 @@ public final class EmptyTargetSource implements TargetSource, Serializable {
// Instance implementation
//---------------------------------------------------------------------
@Nullable
private final Class<?> targetClass;
private final boolean isStatic;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -95,7 +95,8 @@ public class HotSwappableTargetSource implements TargetSource, Serializable {
/**
* Two HotSwappableTargetSources are equal if the current target objects are equal.
* Two HotSwappableTargetSources are equal if the current target
* objects are equal.
*/
@Override
public boolean equals(Object other) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -82,8 +82,14 @@ public class SingletonTargetSource implements TargetSource, Serializable {
*/
@Override
public boolean equals(Object other) {
return (this == other || (other instanceof SingletonTargetSource &&
this.target.equals(((SingletonTargetSource) other).target)));
if (this == other) {
return true;
}
if (!(other instanceof SingletonTargetSource)) {
return false;
}
SingletonTargetSource otherTargetSource = (SingletonTargetSource) other;
return this.target.equals(otherTargetSource.target);
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,12 +58,7 @@ public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource
* is meant to be per thread per instance of the ThreadLocalTargetSource class.
*/
private final ThreadLocal<Object> targetInThread =
new NamedThreadLocal<Object>("Thread-local instance of bean") {
@Override
public String toString() {
return super.toString() + " '" + getTargetBeanName() + "'";
}
};
new NamedThreadLocal<>("Thread-local instance of bean '" + getTargetBeanName() + "'");
/**
* Set of managed targets, enabling us to keep track of the targets we've created.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,7 @@
package org.springframework.aop.framework;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.accessibility.Accessible;
@@ -383,43 +380,6 @@ public class ProxyFactoryTests {
assertThat(proxy.getName()).isEqualTo("tb");
}
@Test
public void testCharSequenceProxy() {
CharSequence target = "test";
ProxyFactory pf = new ProxyFactory(target);
ClassLoader cl = target.getClass().getClassLoader();
CharSequence proxy = (CharSequence) pf.getProxy(cl);
assertThat(proxy.toString()).isEqualTo(target);
}
@Test
public void testDateProxy() {
Date target = new Date();
ProxyFactory pf = new ProxyFactory(target);
pf.setProxyTargetClass(true);
ClassLoader cl = target.getClass().getClassLoader();
Date proxy = (Date) pf.getProxy(cl);
assertThat(proxy.getTime()).isEqualTo(target.getTime());
}
@Test
public void testJdbcSavepointProxy() throws SQLException {
Savepoint target = new Savepoint() {
@Override
public int getSavepointId() throws SQLException {
return 1;
}
@Override
public String getSavepointName() throws SQLException {
return "sp";
}
};
ProxyFactory pf = new ProxyFactory(target);
ClassLoader cl = Savepoint.class.getClassLoader();
Savepoint proxy = (Savepoint) pf.getProxy(cl);
assertThat(proxy.getSavepointName()).isEqualTo("sp");
}
@Order(2)
public static class A implements Runnable {
@@ -431,7 +391,7 @@ public class ProxyFactoryTests {
@Order(1)
public static class B implements Runnable {
public static class B implements Runnable{
@Override
public void run() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -136,10 +136,7 @@ public interface BeanFactory {
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @return an instance of the bean.
* Note that the return value will never be {@code null} but possibly a stub for
* {@code null} returned from a factory method, to be checked via {@code equals(null)}.
* Consider using {@link #getBeanProvider(Class)} for resolving optional dependencies.
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no bean with the specified name
* @throws BeansException if the bean could not be obtained
*/
@@ -155,11 +152,7 @@ public interface BeanFactory {
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean.
* Note that the return value will never be {@code null}. In case of a stub for
* {@code null} from a factory method having been resolved for the requested bean, a
* {@code BeanNotOfRequiredTypeException} against the NullBean stub will be raised.
* Consider using {@link #getBeanProvider(Class)} for resolving optional dependencies.
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -594,7 +594,7 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
* Resolve the specified cached method argument or field value.
*/
@Nullable
private Object resolveCachedArgument(@Nullable String beanName, @Nullable Object cachedArgument) {
private Object resolvedCachedArgument(@Nullable String beanName, @Nullable Object cachedArgument) {
if (cachedArgument instanceof DependencyDescriptor) {
DependencyDescriptor descriptor = (DependencyDescriptor) cachedArgument;
Assert.state(this.beanFactory != null, "No BeanFactory available");
@@ -629,12 +629,10 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
Object value;
if (this.cached) {
try {
value = resolveCachedArgument(beanName, this.cachedFieldValue);
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
catch (BeansException ex) {
// Unexpected target bean mismatch for cached argument -> re-resolve
this.cached = false;
logger.debug("Failed to resolve cached argument", ex);
catch (NoSuchBeanDefinitionException ex) {
// Unexpected removal of target bean for cached argument -> re-resolve
value = resolveFieldValue(field, bean, beanName);
}
}
@@ -663,10 +661,11 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
}
synchronized (this) {
if (!this.cached) {
Object cachedFieldValue = null;
if (value != null || this.required) {
Object cachedFieldValue = desc;
cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
if (value != null && autowiredBeanNames.size() == 1) {
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
@@ -674,13 +673,9 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
desc, autowiredBeanName, field.getType());
}
}
this.cachedFieldValue = cachedFieldValue;
this.cached = true;
}
else {
this.cachedFieldValue = null;
// cached flag remains false
}
this.cachedFieldValue = cachedFieldValue;
this.cached = true;
}
}
return value;
@@ -714,12 +709,10 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
Object[] arguments;
if (this.cached) {
try {
arguments = resolveCachedArguments(beanName, this.cachedMethodArguments);
arguments = resolveCachedArguments(beanName);
}
catch (BeansException ex) {
// Unexpected target bean mismatch for cached argument -> re-resolve
this.cached = false;
logger.debug("Failed to resolve cached argument", ex);
catch (NoSuchBeanDefinitionException ex) {
// Unexpected removal of target bean for cached argument -> re-resolve
arguments = resolveMethodArguments(method, bean, beanName);
}
}
@@ -738,13 +731,14 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
}
@Nullable
private Object[] resolveCachedArguments(@Nullable String beanName, @Nullable Object[] cachedMethodArguments) {
private Object[] resolveCachedArguments(@Nullable String beanName) {
Object[] cachedMethodArguments = this.cachedMethodArguments;
if (cachedMethodArguments == null) {
return null;
}
Object[] arguments = new Object[cachedMethodArguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = resolveCachedArgument(beanName, cachedMethodArguments[i]);
arguments[i] = resolvedCachedArgument(beanName, cachedMethodArguments[i]);
}
return arguments;
}
@@ -777,14 +771,14 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
synchronized (this) {
if (!this.cached) {
if (arguments != null) {
DependencyDescriptor[] cachedMethodArguments = Arrays.copyOf(descriptors, argumentCount);
DependencyDescriptor[] cachedMethodArguments = Arrays.copyOf(descriptors, arguments.length);
registerDependentBeans(beanName, autowiredBeans);
if (autowiredBeans.size() == argumentCount) {
Iterator<String> it = autowiredBeans.iterator();
Class<?>[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
String autowiredBeanName = it.next();
if (arguments[i] != null && beanFactory.containsBean(autowiredBeanName) &&
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
cachedMethodArguments[i] = new ShortcutDependencyDescriptor(
descriptors[i], autowiredBeanName, paramTypes[i]);
@@ -792,12 +786,11 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
}
}
this.cachedMethodArguments = cachedMethodArguments;
this.cached = true;
}
else {
this.cachedMethodArguments = null;
// cached flag remains false
}
this.cached = true;
}
}
return arguments;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -961,7 +961,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
StartupStep smartInitialize = getApplicationStartup().start("spring.beans.smart-initialize")
StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
.tag("beanName", beanName);
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -102,7 +102,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
private boolean singletonsCurrentlyInDestruction = false;
/** Disposable bean instances: bean name to disposable instance. */
private final Map<String, DisposableBean> disposableBeans = new LinkedHashMap<>();
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
/** Map between containing bean names: bean name to Set of bean names that the bean contains. */
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
@@ -340,7 +340,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
* (within the entire factory).
* @param beanName the name of the bean
*/
public boolean isSingletonCurrentlyInCreation(@Nullable String beanName) {
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
@@ -447,17 +447,17 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
}
String canonicalName = canonicalName(beanName);
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans == null || dependentBeans.isEmpty()) {
if (dependentBeans == null) {
return false;
}
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
if (alreadySeen == null) {
alreadySeen = new HashSet<>();
}
alreadySeen.add(beanName);
for (String transitiveDependency : dependentBeans) {
if (alreadySeen == null) {
alreadySeen = new HashSet<>();
}
alreadySeen.add(beanName);
if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
return true;
}
@@ -554,7 +554,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
// Destroy the corresponding DisposableBean instance.
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
disposableBean = this.disposableBeans.remove(beanName);
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
destroyBean(beanName, disposableBean);
}
@@ -68,9 +68,9 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
private static final String SHUTDOWN_METHOD_NAME = "shutdown";
private static final Log logger = LogFactory.getLog(DisposableBeanAdapter.class);
private final Object bean;
private final String beanName;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -506,12 +506,23 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
if (isExternallyManagedInitMethod(initMethod)) {
return true;
}
return hasAnyExternallyManagedMethod(this.externallyManagedInitMethods, initMethod);
if (this.externallyManagedInitMethods != null) {
for (String candidate : this.externallyManagedInitMethods) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot >= 0) {
String methodName = candidate.substring(indexOfDot + 1);
if (methodName.equals(initMethod)) {
return true;
}
}
}
}
return false;
}
}
/**
* Get all externally managed initialization methods (as an immutable Set).
* Return all externally managed initialization methods (as an immutable Set).
* <p>See {@link #registerExternallyManagedInitMethod} for details
* regarding the format for the initialization methods in the returned set.
* @since 5.3.11
@@ -572,23 +583,19 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
if (isExternallyManagedDestroyMethod(destroyMethod)) {
return true;
}
return hasAnyExternallyManagedMethod(this.externallyManagedDestroyMethods, destroyMethod);
}
}
private static boolean hasAnyExternallyManagedMethod(Set<String> candidates, String methodName) {
if (candidates != null) {
for (String candidate : candidates) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot > 0) {
String candidateMethodName = candidate.substring(indexOfDot + 1);
if (candidateMethodName.equals(methodName)) {
return true;
if (this.externallyManagedDestroyMethods != null) {
for (String candidate : this.externallyManagedDestroyMethods) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot >= 0) {
String methodName = candidate.substring(indexOfDot + 1);
if (methodName.equals(destroyMethod)) {
return true;
}
}
}
}
return false;
}
return false;
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -124,89 +124,15 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
ResourceInjectionBean bean = bf.getBean("annotatedBean", ResourceInjectionBean.class);
ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
bean = bf.getBean("annotatedBean", ResourceInjectionBean.class);
bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
}
@Test
public void testResourceInjectionWithNullBean() {
RootBeanDefinition bd = new RootBeanDefinition(NonPublicResourceInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
RootBeanDefinition tb = new RootBeanDefinition(NullFactoryMethods.class);
tb.setFactoryMethodName("createTestBean");
bf.registerBeanDefinition("testBean", tb);
@SuppressWarnings("rawtypes")
NonPublicResourceInjectionBean bean = bf.getBean("annotatedBean", NonPublicResourceInjectionBean.class);
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
bean = bf.getBean("annotatedBean", NonPublicResourceInjectionBean.class);
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
}
@Test
void resourceInjectionWithSometimesNullBean() {
RootBeanDefinition bd = new RootBeanDefinition(OptionalResourceInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
RootBeanDefinition tb = new RootBeanDefinition(SometimesNullFactoryMethods.class);
tb.setFactoryMethodName("createTestBean");
tb.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("testBean", tb);
SometimesNullFactoryMethods.active = false;
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
SometimesNullFactoryMethods.active = true;
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNotNull();
assertThat(bean.getTestBean2()).isNotNull();
assertThat(bean.getTestBean3()).isNotNull();
SometimesNullFactoryMethods.active = false;
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
SometimesNullFactoryMethods.active = false;
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
SometimesNullFactoryMethods.active = true;
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNotNull();
assertThat(bean.getTestBean2()).isNotNull();
assertThat(bean.getTestBean3()).isNotNull();
SometimesNullFactoryMethods.active = true;
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNotNull();
assertThat(bean.getTestBean2()).isNotNull();
assertThat(bean.getTestBean3()).isNotNull();
SometimesNullFactoryMethods.active = false;
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
}
@Test
public void testExtendedResourceInjection() {
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
@@ -217,7 +143,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = bf.getBean("annotatedBean", TypedExtendedResourceInjectionBean.class);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -225,7 +151,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertThat(bean.getBeanFactory()).isSameAs(bf);
bean = bf.getBean("annotatedBean", TypedExtendedResourceInjectionBean.class);
bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -247,7 +173,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean", ntb);
TestBean tb = bf.getBean("testBean", TestBean.class);
TypedExtendedResourceInjectionBean bean = bf.getBean("annotatedBean", TypedExtendedResourceInjectionBean.class);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -274,7 +200,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = bf.getBean("annotatedBean", TypedExtendedResourceInjectionBean.class);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb2);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -292,7 +218,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
OverriddenExtendedResourceInjectionBean bean = bf.getBean("annotatedBean", OverriddenExtendedResourceInjectionBean.class);
OverriddenExtendedResourceInjectionBean bean = (OverriddenExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -312,7 +238,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
DefaultMethodResourceInjectionBean bean = bf.getBean("annotatedBean", DefaultMethodResourceInjectionBean.class);
DefaultMethodResourceInjectionBean bean = (DefaultMethodResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -335,7 +261,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = bf.getBean("annotatedBean", TypedExtendedResourceInjectionBean.class);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -356,7 +282,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -384,7 +310,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -399,7 +325,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.destroySingleton("testBean");
bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
@@ -414,7 +340,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean", tb);
bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -441,7 +367,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
assertThat(bean.getTestBean2()).isSameAs(bf.getBean("testBean"));
assertThat(bean.getTestBean3()).isSameAs(bf.getBean("testBean"));
@@ -456,7 +382,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.removeBeanDefinition("testBean");
bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
@@ -471,7 +397,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
assertThat(bean.getTestBean2()).isSameAs(bf.getBean("testBean"));
assertThat(bean.getTestBean3()).isSameAs(bf.getBean("testBean"));
@@ -500,8 +426,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean2", ntb2);
// Two calls to verify that caching doesn't break re-creation.
OptionalCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -531,8 +457,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean1", ntb1);
// Two calls to verify that caching doesn't break re-creation.
OptionalCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -552,7 +478,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -564,7 +490,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
public void testOptionalResourceInjectionWithNoDependencies() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalResourceInjectionBean.class));
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
@@ -586,7 +512,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
ntb2.setOrder(1);
bf.registerSingleton("nestedTestBean2", ntb2);
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -612,7 +538,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
OptionalResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalResourceInjectionBean.class);
OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -643,8 +569,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean2", ntb2);
// Two calls to verify that caching doesn't break re-creation.
OptionalCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -676,8 +602,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean2", ntb2);
// Two calls to verify that caching doesn't break re-creation.
OptionalCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
bean = bf.getBean("annotatedBean", OptionalCollectionResourceInjectionBean.class);
OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -704,7 +630,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
ConstructorResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -712,7 +638,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertThat(bean.getBeanFactory()).isSameAs(bf);
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -731,7 +657,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
ConstructorResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -741,7 +667,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.destroySingleton("nestedTestBean");
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -751,7 +677,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean", ntb);
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -769,7 +695,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean", tb);
bf.registerBeanDefinition("nestedTestBean", new RootBeanDefinition(NestedTestBean.class));
ConstructorResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -779,7 +705,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.removeBeanDefinition("nestedTestBean");
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -789,7 +715,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("nestedTestBean", new RootBeanDefinition(NestedTestBean.class));
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -808,7 +734,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("nestedTestBean", new RootBeanDefinition(NullNestedTestBeanFactoryBean.class));
bf.registerSingleton("nestedTestBean2", new NestedTestBean());
ConstructorResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -816,7 +742,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.getNestedTestBean()).isNull();
assertThat(bean.getBeanFactory()).isSameAs(bf);
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
@@ -838,7 +764,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("nestedTestBean", ntb);
bf.registerSingleton("nestedTestBean2", new NestedTestBean());
ConstructorResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
@@ -846,7 +772,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.getNestedTestBean()).isNull();
assertThat(bean.getBeanFactory()).isSameAs(bf);
bean = bf.getBean("annotatedBean", ConstructorResourceInjectionBean.class);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isNull();
assertThat(bean.getTestBean2()).isNull();
assertThat(bean.getTestBean3()).isNull();
@@ -865,7 +791,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsResourceInjectionBean.class);
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isNull();
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().length).isEqualTo(2);
@@ -876,8 +802,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@Test
public void testConstructorResourceInjectionWithNoCandidatesAndNoFallback() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorWithoutFallbackBean.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> bf.getBean("annotatedBean"))
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(ConstructorWithoutFallbackBean.class));
}
@@ -891,7 +817,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsCollectionResourceInjectionBean.class);
ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isNull();
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().size()).isEqualTo(1);
@@ -913,7 +839,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsCollectionResourceInjectionBean.class);
ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isNull();
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().size()).isEqualTo(2);
@@ -931,7 +857,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsResourceInjectionBean.class);
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isNull();
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().length).isEqualTo(2);
@@ -949,7 +875,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsCollectionResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsCollectionResourceInjectionBean.class);
ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isNull();
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().size()).isEqualTo(2);
@@ -967,7 +893,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
SingleConstructorVarargBean bean = bf.getBean("annotatedBean", SingleConstructorVarargBean.class);
SingleConstructorVarargBean bean = (SingleConstructorVarargBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().size()).isEqualTo(2);
assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2);
@@ -980,7 +906,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
SingleConstructorVarargBean bean = bf.getBean("annotatedBean", SingleConstructorVarargBean.class);
SingleConstructorVarargBean bean = (SingleConstructorVarargBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getNestedTestBeans()).isNotNull();
assertThat(bean.getNestedTestBeans().isEmpty()).isTrue();
@@ -996,7 +922,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
SingleConstructorRequiredCollectionBean bean = bf.getBean("annotatedBean", SingleConstructorRequiredCollectionBean.class);
SingleConstructorRequiredCollectionBean bean = (SingleConstructorRequiredCollectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().size()).isEqualTo(2);
assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2);
@@ -1009,7 +935,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
SingleConstructorRequiredCollectionBean bean = bf.getBean("annotatedBean", SingleConstructorRequiredCollectionBean.class);
SingleConstructorRequiredCollectionBean bean = (SingleConstructorRequiredCollectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getNestedTestBeans()).isNotNull();
assertThat(bean.getNestedTestBeans().isEmpty()).isTrue();
@@ -1025,7 +951,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
SingleConstructorOptionalCollectionBean bean = bf.getBean("annotatedBean", SingleConstructorOptionalCollectionBean.class);
SingleConstructorOptionalCollectionBean bean = (SingleConstructorOptionalCollectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getNestedTestBeans().size()).isEqualTo(2);
assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2);
@@ -1038,7 +964,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
SingleConstructorOptionalCollectionBean bean = bf.getBean("annotatedBean", SingleConstructorOptionalCollectionBean.class);
SingleConstructorOptionalCollectionBean bean = (SingleConstructorOptionalCollectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getNestedTestBeans()).isNull();
}
@@ -1046,8 +972,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@Test
public void testSingleConstructorInjectionWithMissingDependency() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SingleConstructorOptionalCollectionBean.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> bf.getBean("annotatedBean"));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("annotatedBean"));
}
@Test
@@ -1056,8 +982,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
RootBeanDefinition tb = new RootBeanDefinition(NullFactoryMethods.class);
tb.setFactoryMethodName("createTestBean");
bf.registerBeanDefinition("testBean", tb);
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> bf.getBean("annotatedBean"));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("annotatedBean"));
}
@Test
@@ -1066,7 +992,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
ConstructorsResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsResourceInjectionBean.class);
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isSameAs(tb);
assertThat(bean.getTestBean4()).isNull();
}
@@ -1075,7 +1001,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
public void testConstructorResourceInjectionWithMultipleCandidatesAndDefaultFallback() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorsResourceInjectionBean.class));
ConstructorsResourceInjectionBean bean = bf.getBean("annotatedBean", ConstructorsResourceInjectionBean.class);
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean3()).isNull();
assertThat(bean.getTestBean4()).isNull();
}
@@ -1091,12 +1017,12 @@ public class AutowiredAnnotationBeanPostProcessorTests {
tb2.setFactoryMethodName("createTestBean");
bf.registerBeanDefinition("testBean2", tb2);
MapConstructorInjectionBean bean = bf.getBean("annotatedBean", MapConstructorInjectionBean.class);
MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertThat(bean.getTestBeanMap().get("testBean1")).isSameAs(tb1);
assertThat(bean.getTestBeanMap().get("testBean2")).isNull();
bean = bf.getBean("annotatedBean", MapConstructorInjectionBean.class);
bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertThat(bean.getTestBeanMap().get("testBean1")).isSameAs(tb1);
assertThat(bean.getTestBeanMap().get("testBean2")).isNull();
@@ -1112,14 +1038,14 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean1", tb1);
bf.registerSingleton("testBean2", tb2);
MapFieldInjectionBean bean = bf.getBean("annotatedBean", MapFieldInjectionBean.class);
MapFieldInjectionBean bean = (MapFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap().size()).isEqualTo(2);
assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue();
assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue();
assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue();
bean = bf.getBean("annotatedBean", MapFieldInjectionBean.class);
bean = (MapFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap().size()).isEqualTo(2);
assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue();
@@ -1135,13 +1061,13 @@ public class AutowiredAnnotationBeanPostProcessorTests {
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue();
assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue();
assertThat(bean.getTestBean()).isSameAs(tb);
bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue();
assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue();
@@ -1153,9 +1079,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).as("should have failed, more than one bean of type")
.isThrownBy(() -> bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(MapMethodInjectionBean.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).as("should have failed, more than one bean of type").isThrownBy(() ->
bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(MapMethodInjectionBean.class));
}
@Test
@@ -1166,8 +1092,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
rbd2.setAutowireCandidate(false);
bf.registerBeanDefinition("testBean2", rbd2);
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
TestBean tb = bf.getBean("testBean1", TestBean.class);
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
TestBean tb = (TestBean) bf.getBean("testBean1");
assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue();
@@ -1178,7 +1104,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
public void testMethodInjectionWithMapAndNoMatches() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isNull();
assertThat(bean.getTestBean()).isNull();
}
@@ -1194,9 +1120,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBeans", tbm);
bf.registerSingleton("otherMap", new Properties());
MapConstructorInjectionBean bean = bf.getBean("annotatedBean", MapConstructorInjectionBean.class);
MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(tbm);
bean = bf.getBean("annotatedBean", MapConstructorInjectionBean.class);
bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(tbm);
}
@@ -1210,9 +1136,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("myTestBeanMap", tbm);
bf.registerSingleton("otherMap", new HashMap<>());
MapConstructorInjectionBean bean = bf.getBean("annotatedBean", MapConstructorInjectionBean.class);
MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
bean = bf.getBean("annotatedBean", MapConstructorInjectionBean.class);
bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
}
@@ -1227,9 +1153,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean1", new TestBean());
bf.registerSingleton("testBean2", new TestBean());
CustomMapConstructorInjectionBean bean = bf.getBean("annotatedBean", CustomMapConstructorInjectionBean.class);
CustomMapConstructorInjectionBean bean = (CustomMapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
bean = bf.getBean("annotatedBean", CustomMapConstructorInjectionBean.class);
bean = (CustomMapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
}
@@ -1240,9 +1166,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", bd);
bf.registerBeanDefinition("myTestBeanMap", new RootBeanDefinition(HashMap.class));
QualifiedMapConstructorInjectionBean bean = bf.getBean("annotatedBean", QualifiedMapConstructorInjectionBean.class);
QualifiedMapConstructorInjectionBean bean = (QualifiedMapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
bean = bf.getBean("annotatedBean", QualifiedMapConstructorInjectionBean.class);
bean = (QualifiedMapConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
}
@@ -1257,9 +1183,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBeans", tbs);
bf.registerSingleton("otherSet", new HashSet<>());
SetConstructorInjectionBean bean = bf.getBean("annotatedBean", SetConstructorInjectionBean.class);
SetConstructorInjectionBean bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanSet()).isSameAs(tbs);
bean = bf.getBean("annotatedBean", SetConstructorInjectionBean.class);
bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanSet()).isSameAs(tbs);
}
@@ -1273,9 +1199,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("myTestBeanSet", tbs);
bf.registerSingleton("otherSet", new HashSet<>());
SetConstructorInjectionBean bean = bf.getBean("annotatedBean", SetConstructorInjectionBean.class);
SetConstructorInjectionBean bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet"));
bean = bf.getBean("annotatedBean", SetConstructorInjectionBean.class);
bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet"));
}
@@ -1288,9 +1214,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
tbs.setUniqueFactoryMethodName("testBeanSet");
bf.registerBeanDefinition("myTestBeanSet", tbs);
CustomSetConstructorInjectionBean bean = bf.getBean("annotatedBean", CustomSetConstructorInjectionBean.class);
CustomSetConstructorInjectionBean bean = (CustomSetConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet"));
bean = bf.getBean("annotatedBean", CustomSetConstructorInjectionBean.class);
bean = (CustomSetConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet"));
}
@@ -1298,7 +1224,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
public void testSelfReference() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionBean.class));
SelfInjectionBean bean = bf.getBean("annotatedBean", SelfInjectionBean.class);
SelfInjectionBean bean = (SelfInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.reference).isSameAs(bean);
assertThat(bean.referenceCollection).isNull();
}
@@ -1308,8 +1234,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionBean.class));
bf.registerBeanDefinition("annotatedBean2", new RootBeanDefinition(SelfInjectionBean.class));
SelfInjectionBean bean = bf.getBean("annotatedBean", SelfInjectionBean.class);
SelfInjectionBean bean2 = bf.getBean("annotatedBean2", SelfInjectionBean.class);
SelfInjectionBean bean = (SelfInjectionBean) bf.getBean("annotatedBean");
SelfInjectionBean bean2 = (SelfInjectionBean) bf.getBean("annotatedBean2");
assertThat(bean.reference).isSameAs(bean2);
assertThat(bean.referenceCollection.size()).isEqualTo(1);
assertThat(bean.referenceCollection.get(0)).isSameAs(bean2);
@@ -1319,7 +1245,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
public void testSelfReferenceCollection() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionCollectionBean.class));
SelfInjectionCollectionBean bean = bf.getBean("annotatedBean", SelfInjectionCollectionBean.class);
SelfInjectionCollectionBean bean = (SelfInjectionCollectionBean) bf.getBean("annotatedBean");
assertThat(bean.reference).isSameAs(bean);
assertThat(bean.referenceCollection).isNull();
}
@@ -1329,8 +1255,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionCollectionBean.class));
bf.registerBeanDefinition("annotatedBean2", new RootBeanDefinition(SelfInjectionCollectionBean.class));
SelfInjectionCollectionBean bean = bf.getBean("annotatedBean", SelfInjectionCollectionBean.class);
SelfInjectionCollectionBean bean2 = bf.getBean("annotatedBean2", SelfInjectionCollectionBean.class);
SelfInjectionCollectionBean bean = (SelfInjectionCollectionBean) bf.getBean("annotatedBean");
SelfInjectionCollectionBean bean2 = (SelfInjectionCollectionBean) bf.getBean("annotatedBean2");
assertThat(bean.reference).isSameAs(bean2);
assertThat(bean2.referenceCollection.size()).isSameAs(1);
assertThat(bean.referenceCollection.get(0)).isSameAs(bean2);
@@ -1341,7 +1267,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ObjectFactoryFieldInjectionBean bean = bf.getBean("annotatedBean", ObjectFactoryFieldInjectionBean.class);
ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
}
@@ -1350,7 +1276,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryConstructorInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ObjectFactoryConstructorInjectionBean bean = bf.getBean("annotatedBean", ObjectFactoryConstructorInjectionBean.class);
ObjectFactoryConstructorInjectionBean bean = (ObjectFactoryConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
}
@@ -1361,9 +1287,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", annotatedBeanDefinition);
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ObjectFactoryFieldInjectionBean bean = bf.getBean("annotatedBean", ObjectFactoryFieldInjectionBean.class);
ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
ObjectFactoryFieldInjectionBean anotherBean = bf.getBean("annotatedBean", ObjectFactoryFieldInjectionBean.class);
ObjectFactoryFieldInjectionBean anotherBean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean).isNotSameAs(anotherBean);
assertThat(anotherBean.getTestBean()).isSameAs(bf.getBean("testBean"));
}
@@ -1376,7 +1302,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("dependencyBean", bd);
bf.registerBeanDefinition("dependencyBean2", new RootBeanDefinition(TestBean.class));
ObjectFactoryQualifierInjectionBean bean = bf.getBean("annotatedBean", ObjectFactoryQualifierInjectionBean.class);
ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("dependencyBean"));
}
@@ -1388,7 +1314,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("dependencyBean", bd);
bf.registerBeanDefinition("dependencyBean2", new RootBeanDefinition(TestBean.class));
ObjectFactoryQualifierInjectionBean bean = bf.getBean("annotatedBean", ObjectFactoryQualifierInjectionBean.class);
ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("dependencyBean"));
}
@@ -1398,7 +1324,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
ObjectFactoryFieldInjectionBean bean = bf.getBean("annotatedBean", ObjectFactoryFieldInjectionBean.class);
ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = SerializationTestUtils.serializeAndDeserialize(bean);
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
@@ -1411,7 +1337,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("testBean", tbd);
ObjectProviderInjectionBean bean = bf.getBean("annotatedBean", ObjectProviderInjectionBean.class);
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isEqualTo(bf.getBean("testBean"));
assertThat(bean.getTestBean("myName")).isEqualTo(bf.getBean("testBean", "myName"));
assertThat(bean.getOptionalTestBean()).isEqualTo(bf.getBean("testBean"));
@@ -1440,7 +1366,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectProviderInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ObjectProviderInjectionBean bean = bf.getBean("annotatedBean", ObjectProviderInjectionBean.class);
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
assertThat(bean.getOptionalTestBean()).isSameAs(bf.getBean("testBean"));
assertThat(bean.getOptionalTestBeanWithDefault()).isSameAs(bf.getBean("testBean"));
@@ -1467,7 +1393,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
public void testObjectProviderInjectionWithTargetNotAvailable() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectProviderInjectionBean.class));
ObjectProviderInjectionBean bean = bf.getBean("annotatedBean", ObjectProviderInjectionBean.class);
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(
bean::getTestBean);
assertThat(bean.getOptionalTestBean()).isNull();
@@ -1493,7 +1419,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
ObjectProviderInjectionBean bean = bf.getBean("annotatedBean", ObjectProviderInjectionBean.class);
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getTestBean);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getOptionalTestBean);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::consumeOptionalTestBean);
@@ -1530,7 +1456,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
tb2.setLazyInit(true);
bf.registerBeanDefinition("testBean2", tb2);
ObjectProviderInjectionBean bean = bf.getBean("annotatedBean", ObjectProviderInjectionBean.class);
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean1"));
assertThat(bean.getOptionalTestBean()).isSameAs(bf.getBean("testBean1"));
assertThat(bean.consumeOptionalTestBean()).isSameAs(bf.getBean("testBean1"));
@@ -1568,7 +1494,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
tb2.setLazyInit(true);
bf.registerBeanDefinition("testBean2", tb2);
ObjectProviderInjectionBean bean = bf.getBean("annotatedBean", ObjectProviderInjectionBean.class);
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
List<?> testBeans = bean.sortedTestBeans();
assertThat(testBeans.size()).isEqualTo(2);
assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean2"));
@@ -1791,7 +1717,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
IntegerRepository ir = new IntegerRepository();
bf.registerSingleton("integerRepo", ir);
RepositoryFieldInjectionBean bean = bf.getBean("annotatedBean", RepositoryFieldInjectionBean.class);
RepositoryFieldInjectionBean bean = (RepositoryFieldInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.string).isSameAs(sv);
assertThat(bean.integer).isSameAs(iv);
assertThat(bean.stringArray.length).isSameAs(1);
@@ -1836,8 +1762,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
IntegerRepository ir = new IntegerRepository();
bf.registerSingleton("integerRepo", ir);
RepositoryFieldInjectionBeanWithSubstitutedVariables bean =
bf.getBean("annotatedBean", RepositoryFieldInjectionBeanWithSubstitutedVariables.class);
RepositoryFieldInjectionBeanWithSubstitutedVariables bean = (RepositoryFieldInjectionBeanWithSubstitutedVariables) bf.getBean("annotatedBean");
assertThat(bean.string).isSameAs(sv);
assertThat(bean.integer).isSameAs(iv);
assertThat(bean.stringArray.length).isSameAs(1);
@@ -1878,8 +1803,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
IntegerRepository ir = new IntegerRepository();
bf.registerSingleton("integerRepo", ir);
RepositoryFieldInjectionBeanWithQualifiers bean =
bf.getBean("annotatedBean", RepositoryFieldInjectionBeanWithQualifiers.class);
RepositoryFieldInjectionBeanWithQualifiers bean = (RepositoryFieldInjectionBeanWithQualifiers) bf.getBean("annotatedBean");
assertThat(bean.stringRepository).isSameAs(sr);
assertThat(bean.integerRepository).isSameAs(ir);
assertThat(bean.stringRepositoryArray.length).isSameAs(1);
@@ -1916,8 +1840,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
rbd.setQualifiedElement(ReflectionUtils.findField(getClass(), "integerRepositoryQualifierProvider"));
bf.registerBeanDefinition("integerRepository", rbd); // Bean name not matching qualifier
RepositoryFieldInjectionBeanWithQualifiers bean =
bf.getBean("annotatedBean", RepositoryFieldInjectionBeanWithQualifiers.class);
RepositoryFieldInjectionBeanWithQualifiers bean = (RepositoryFieldInjectionBeanWithQualifiers) bf.getBean("annotatedBean");
Repository<?> sr = bf.getBean("stringRepo", Repository.class);
Repository<?> ir = bf.getBean("integerRepository", Repository.class);
assertThat(bean.stringRepository).isSameAs(sr);
@@ -1944,8 +1867,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("repo", new StringRepository());
RepositoryFieldInjectionBeanWithSimpleMatch bean =
bf.getBean("annotatedBean", RepositoryFieldInjectionBeanWithSimpleMatch.class);
RepositoryFieldInjectionBeanWithSimpleMatch bean = (RepositoryFieldInjectionBeanWithSimpleMatch) bf.getBean("annotatedBean");
Repository<?> repo = bf.getBean("repo", Repository.class);
assertThat(bean.repository).isSameAs(repo);
assertThat(bean.stringRepository).isSameAs(repo);
@@ -1972,7 +1894,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", bd);
bf.registerBeanDefinition("repoFactoryBean", new RootBeanDefinition(RepositoryFactoryBean.class));
RepositoryFactoryBeanInjectionBean bean = bf.getBean("annotatedBean", RepositoryFactoryBeanInjectionBean.class);
RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) bf.getBean("annotatedBean");
RepositoryFactoryBean<?> repoFactoryBean = bf.getBean("&repoFactoryBean", RepositoryFactoryBean.class);
assertThat(bean.repositoryFactoryBean).isSameAs(repoFactoryBean);
}
@@ -1984,7 +1906,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", bd);
bf.registerSingleton("repoFactoryBean", new RepositoryFactoryBean<>());
RepositoryFactoryBeanInjectionBean bean = bf.getBean("annotatedBean", RepositoryFactoryBeanInjectionBean.class);
RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) bf.getBean("annotatedBean");
RepositoryFactoryBean<?> repoFactoryBean = bf.getBean("&repoFactoryBean", RepositoryFactoryBean.class);
assertThat(bean.repositoryFactoryBean).isSameAs(repoFactoryBean);
}
@@ -2003,7 +1925,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
rbd.getConstructorArgumentValues().addGenericArgumentValue(Repository.class);
bf.registerBeanDefinition("repo", rbd);
RepositoryFieldInjectionBeanWithSimpleMatch bean = bf.getBean("annotatedBean", RepositoryFieldInjectionBeanWithSimpleMatch.class);
RepositoryFieldInjectionBeanWithSimpleMatch bean = (RepositoryFieldInjectionBeanWithSimpleMatch) bf.getBean("annotatedBean");
Repository<?> repo = bf.getBean("repo", Repository.class);
assertThat(bean.repository).isSameAs(repo);
assertThat(bean.stringRepository).isSameAs(repo);
@@ -2034,7 +1956,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
rbd.getConstructorArgumentValues().addGenericArgumentValue(new TypedStringValue(Repository.class.getName()));
bf.registerBeanDefinition("repo", rbd);
RepositoryFieldInjectionBeanWithSimpleMatch bean = bf.getBean("annotatedBean", RepositoryFieldInjectionBeanWithSimpleMatch.class);
RepositoryFieldInjectionBeanWithSimpleMatch bean = (RepositoryFieldInjectionBeanWithSimpleMatch) bf.getBean("annotatedBean");
Repository<?> repo = bf.getBean("repo", Repository.class);
assertThat(bean.repository).isSameAs(repo);
assertThat(bean.stringRepository).isSameAs(repo);
@@ -2066,7 +1988,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
IntegerRepository ir = new IntegerRepository();
bf.registerSingleton("integerRepo", ir);
RepositoryMethodInjectionBean bean = bf.getBean("annotatedBean", RepositoryMethodInjectionBean.class);
RepositoryMethodInjectionBean bean = (RepositoryMethodInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.string).isSameAs(sv);
assertThat(bean.integer).isSameAs(iv);
assertThat(bean.stringArray.length).isSameAs(1);
@@ -2111,8 +2033,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
IntegerRepository ir = new IntegerRepository();
bf.registerSingleton("integerRepo", ir);
RepositoryMethodInjectionBeanWithSubstitutedVariables bean =
bf.getBean("annotatedBean", RepositoryMethodInjectionBeanWithSubstitutedVariables.class);
RepositoryMethodInjectionBeanWithSubstitutedVariables bean = (RepositoryMethodInjectionBeanWithSubstitutedVariables) bf.getBean("annotatedBean");
assertThat(bean.string).isSameAs(sv);
assertThat(bean.integer).isSameAs(iv);
assertThat(bean.stringArray.length).isSameAs(1);
@@ -2153,7 +2074,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
IntegerRepository ir = new IntegerRepository();
bf.registerSingleton("integerRepo", ir);
RepositoryConstructorInjectionBean bean = bf.getBean("annotatedBean", RepositoryConstructorInjectionBean.class);
RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.stringRepository).isSameAs(sr);
assertThat(bean.integerRepository).isSameAs(ir);
assertThat(bean.stringRepositoryArray.length).isSameAs(1);
@@ -2179,7 +2100,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
GenericRepository gr = new GenericRepository();
bf.registerSingleton("genericRepo", gr);
RepositoryConstructorInjectionBean bean = bf.getBean("annotatedBean", RepositoryConstructorInjectionBean.class);
RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.stringRepository).isSameAs(gr);
assertThat(bean.integerRepository).isSameAs(gr);
assertThat(bean.stringRepositoryArray.length).isSameAs(1);
@@ -2204,7 +2125,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
SimpleRepository ngr = new SimpleRepository();
bf.registerSingleton("simpleRepo", ngr);
RepositoryConstructorInjectionBean bean = bf.getBean("annotatedBean", RepositoryConstructorInjectionBean.class);
RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.stringRepository).isSameAs(ngr);
assertThat(bean.integerRepository).isSameAs(ngr);
assertThat(bean.stringRepositoryArray.length).isSameAs(1);
@@ -2232,7 +2153,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
GenericRepository gr = new GenericRepositorySubclass();
bf.registerSingleton("genericRepo", gr);
RepositoryConstructorInjectionBean bean = bf.getBean("annotatedBean", RepositoryConstructorInjectionBean.class);
RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.stringRepository).isSameAs(sr);
assertThat(bean.integerRepository).isSameAs(gr);
assertThat(bean.stringRepositoryArray.length).isSameAs(1);
@@ -2259,7 +2180,7 @@ public class AutowiredAnnotationBeanPostProcessorTests {
SimpleRepository ngr = new SimpleRepositorySubclass();
bf.registerSingleton("simpleRepo", ngr);
RepositoryConstructorInjectionBean bean = bf.getBean("annotatedBean", RepositoryConstructorInjectionBean.class);
RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.stringRepository).isSameAs(sr);
assertThat(bean.integerRepository).isSameAs(ngr);
assertThat(bean.stringRepositoryArray.length).isSameAs(1);
@@ -3955,20 +3876,6 @@ public class AutowiredAnnotationBeanPostProcessorTests {
}
public static class SometimesNullFactoryMethods {
public static boolean active = false;
public static TestBean createTestBean() {
return (active ? new TestBean() : null);
}
public static NestedTestBean createNestedTestBean() {
return (active ? new NestedTestBean() : null);
}
}
public static class ProvidedArgumentBean {
public ProvidedArgumentBean(String[] args) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,32 +28,36 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Chris Beams
* @since 04.07.2006
*/
class DefaultSingletonBeanRegistryTests {
private final DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();
public class DefaultSingletonBeanRegistryTests {
@Test
void singletons() {
public void testSingletons() {
DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();
TestBean tb = new TestBean();
beanRegistry.registerSingleton("tb", tb);
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", TestBean::new);
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", () -> new TestBean());
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
assertThat(beanRegistry.getSingletonCount()).isEqualTo(2);
assertThat(beanRegistry.getSingletonNames()).containsExactly("tb", "tb2");
String[] names = beanRegistry.getSingletonNames();
assertThat(names.length).isEqualTo(2);
assertThat(names[0]).isEqualTo("tb");
assertThat(names[1]).isEqualTo("tb2");
beanRegistry.destroySingletons();
assertThat(beanRegistry.getSingletonCount()).isZero();
assertThat(beanRegistry.getSingletonNames()).isEmpty();
assertThat(beanRegistry.getSingletonCount()).isEqualTo(0);
assertThat(beanRegistry.getSingletonNames().length).isEqualTo(0);
}
@Test
void disposableBean() {
public void testDisposableBean() {
DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();
DerivedTestBean tb = new DerivedTestBean();
beanRegistry.registerSingleton("tb", tb);
beanRegistry.registerDisposableBean("tb", tb);
@@ -61,16 +65,21 @@ class DefaultSingletonBeanRegistryTests {
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
assertThat(beanRegistry.getSingletonCount()).isEqualTo(1);
assertThat(beanRegistry.getSingletonNames()).containsExactly("tb");
String[] names = beanRegistry.getSingletonNames();
assertThat(names.length).isEqualTo(1);
assertThat(names[0]).isEqualTo("tb");
assertThat(tb.wasDestroyed()).isFalse();
beanRegistry.destroySingletons();
assertThat(beanRegistry.getSingletonCount()).isZero();
assertThat(beanRegistry.getSingletonNames()).isEmpty();
assertThat(beanRegistry.getSingletonCount()).isEqualTo(0);
assertThat(beanRegistry.getSingletonNames().length).isEqualTo(0);
assertThat(tb.wasDestroyed()).isTrue();
}
@Test
void dependentRegistration() {
public void testDependentRegistration() {
DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();
beanRegistry.registerDependentBean("a", "b");
beanRegistry.registerDependentBean("b", "c");
beanRegistry.registerDependentBean("c", "b");
@@ -189,11 +189,13 @@ public class CaffeineCacheManager implements CacheManager {
@Override
@Nullable
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache == null && this.dynamic) {
cache = this.cacheMap.computeIfAbsent(name, this::createCaffeineCache);
if (this.dynamic) {
Cache cache = this.cacheMap.get(name);
return (cache != null) ? cache : this.cacheMap.computeIfAbsent(name, this::createCaffeineCache);
}
else {
return this.cacheMap.get(name);
}
return cache;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -166,7 +166,13 @@ public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderA
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache == null && this.dynamic) {
cache = this.cacheMap.computeIfAbsent(name, this::createConcurrentMapCache);
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
cache = createConcurrentMapCache(name);
this.cacheMap.put(name, cache);
}
}
}
return cache;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,7 +47,7 @@ public class NameMatchCacheOperationSource implements CacheOperationSource, Seri
/** Keys are method names; values are TransactionAttributes. */
private final Map<String, Collection<CacheOperation>> nameMap = new LinkedHashMap<>();
private Map<String, Collection<CacheOperation>> nameMap = new LinkedHashMap<>();
/**
@@ -117,8 +117,8 @@ public class NameMatchCacheOperationSource implements CacheOperationSource, Seri
if (!(other instanceof NameMatchCacheOperationSource)) {
return false;
}
NameMatchCacheOperationSource otherCos = (NameMatchCacheOperationSource) other;
return ObjectUtils.nullSafeEquals(this.nameMap, otherCos.nameMap);
NameMatchCacheOperationSource otherTas = (NameMatchCacheOperationSource) other;
return ObjectUtils.nullSafeEquals(this.nameMap, otherTas.nameMap);
}
@Override
@@ -130,5 +130,4 @@ public class NameMatchCacheOperationSource implements CacheOperationSource, Seri
public String toString() {
return getClass().getName() + ": " + this.nameMap;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@ import org.springframework.instrument.classloading.LoadTimeWeaver;
/**
* Interface to be implemented by
* {@link org.springframework.context.annotation.Configuration @Configuration}
* classes annotated with {@link EnableLoadTimeWeaving @EnableLoadTimeWeaving}
* that wish to customize the {@link LoadTimeWeaver} instance to be used.
* classes annotated with {@link EnableLoadTimeWeaving @EnableLoadTimeWeaving} that wish to
* customize the {@link LoadTimeWeaver} instance to be used.
*
* <p>See {@link org.springframework.scheduling.annotation.EnableAsync @EnableAsync}
* for usage examples and information on how a default {@code LoadTimeWeaver}
@@ -36,9 +36,9 @@ import org.springframework.instrument.classloading.LoadTimeWeaver;
public interface LoadTimeWeavingConfigurer {
/**
* Create, configure and return the {@code LoadTimeWeaver} instance to be used.
* Note that it is unnecessary to annotate this method with {@code @Bean}
* because the object returned will automatically be registered as a bean by
* Create, configure and return the {@code LoadTimeWeaver} instance to be used. Note
* that it is unnecessary to annotate this method with {@code @Bean}, because the
* object returned will automatically be registered as a bean by
* {@link LoadTimeWeavingConfiguration#loadTimeWeaver()}
*/
LoadTimeWeaver getLoadTimeWeaver();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -274,7 +274,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
handleAsyncError(ex);
}
else if (event != null) {
publishEvents(event);
publishEvent(event);
}
});
}
@@ -367,7 +367,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
* Return the target bean instance to use.
*/
protected Object getTargetBean() {
Assert.notNull(this.applicationContext, "ApplicationContext must not be null");
Assert.notNull(this.applicationContext, "ApplicationContext must no be null");
return this.applicationContext.getBean(this.beanName);
}
@@ -468,9 +468,6 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
}
/**
* Inner class to avoid a hard dependency on the Reactive Streams API at runtime.
*/
private class ReactiveResultHandler {
public boolean subscribeToPublisher(Object result) {
@@ -484,9 +481,6 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
}
/**
* Reactive Streams Subscriber for publishing follow-up events.
*/
private class EventPublicationSubscriber implements Subscriber<Object> {
@Override
@@ -447,7 +447,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
@Override
public void setApplicationStartup(ApplicationStartup applicationStartup) {
Assert.notNull(applicationStartup, "ApplicationStartup must not be null");
Assert.notNull(applicationStartup, "applicationStartup should not be null");
this.applicationStartup = applicationStartup;
}
@@ -749,8 +749,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null &&
beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,6 @@ import java.security.ProtectionDomain;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.DecoratingClassLoader;
import org.springframework.core.OverridingClassLoader;
import org.springframework.core.SmartClassLoader;
@@ -47,26 +45,15 @@ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements Smart
}
@Nullable
private static final Method findLoadedClassMethod;
private static Method findLoadedClassMethod;
static {
// Try to enable findLoadedClass optimization which allows us to selectively
// override classes that have not been loaded yet. If not accessible, we will
// always override requested classes, even when the classes have been loaded
// by the parent ClassLoader already and cannot be transformed anymore anyway.
Method method = null;
try {
method = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
ReflectionUtils.makeAccessible(method);
findLoadedClassMethod = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
}
catch (Throwable ex) {
// Typically a JDK 9+ InaccessibleObjectException...
// Avoid through JVM startup with --add-opens=java.base/java.lang=ALL-UNNAMED
LogFactory.getLog(ContextTypeMatchClassLoader.class).debug(
"ClassLoader.findLoadedClass not accessible -> will always override requested class", ex);
catch (NoSuchMethodException ex) {
throw new IllegalStateException("Invalid [java.lang.ClassLoader] class: no 'findLoadedClass' method defined!");
}
findLoadedClassMethod = method;
}
@@ -109,14 +96,13 @@ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements Smart
if (isExcluded(className) || ContextTypeMatchClassLoader.this.isExcluded(className)) {
return false;
}
if (findLoadedClassMethod != null) {
ClassLoader parent = getParent();
while (parent != null) {
if (ReflectionUtils.invokeMethod(findLoadedClassMethod, parent, className) != null) {
return false;
}
parent = parent.getParent();
ReflectionUtils.makeAccessible(findLoadedClassMethod);
ClassLoader parent = getParent();
while (parent != null) {
if (ReflectionUtils.invokeMethod(findLoadedClassMethod, parent, className) != null) {
return false;
}
parent = parent.getParent();
}
return true;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -64,10 +64,9 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
/**
* Specify the maximum time allotted in milliseconds for the shutdown of any
* phase (group of {@link SmartLifecycle} beans with the same 'phase' value).
* <p>The default value is 30000 milliseconds (30 seconds).
* @see SmartLifecycle#getPhase()
* Specify the maximum time allotted in milliseconds for the shutdown of
* any phase (group of SmartLifecycle beans with the same 'phase' value).
* <p>The default value is 30 seconds.
*/
public void setTimeoutPerShutdownPhase(long timeoutPerShutdownPhase) {
this.timeoutPerShutdownPhase = timeoutPerShutdownPhase;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -117,12 +117,9 @@ public @interface Scheduled {
* last invocation and the start of the next.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* <p>This attribute variant supports Spring-style "${...}" placeholders
* as well as SpEL expressions.
* @return the delay as a String value &mdash; for example, a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
* @see #fixedDelay()
*/
String fixedDelayString() default "";
@@ -138,12 +135,9 @@ public @interface Scheduled {
* Execute the annotated method with a fixed period between invocations.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* <p>This attribute variant supports Spring-style "${...}" placeholders
* as well as SpEL expressions.
* @return the period as a String value &mdash; for example, a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
* @see #fixedRate()
*/
String fixedRateString() default "";
@@ -162,12 +156,9 @@ public @interface Scheduled {
* {@link #fixedRate} or {@link #fixedDelay} task.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* <p>This attribute variant supports Spring-style "${...}" placeholders
* as well as SpEL expressions.
* @return the initial delay as a String value &mdash; for example, a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
* @see #initialDelay()
*/
String initialDelayString() default "";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -83,9 +83,6 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
private TaskExecutorAdapter adaptedExecutor;
@Nullable
private TaskDecorator taskDecorator;
/**
* Create a new ConcurrentTaskExecutor, using a single thread executor as default.
@@ -141,7 +138,6 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
* @since 4.3
*/
public final void setTaskDecorator(TaskDecorator taskDecorator) {
this.taskDecorator = taskDecorator;
this.adaptedExecutor.setTaskDecorator(taskDecorator);
}
@@ -178,15 +174,11 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
}
private TaskExecutorAdapter getAdaptedExecutor(Executor concurrentExecutor) {
private static TaskExecutorAdapter getAdaptedExecutor(Executor concurrentExecutor) {
if (managedExecutorServiceClass != null && managedExecutorServiceClass.isInstance(concurrentExecutor)) {
return new ManagedTaskExecutorAdapter(concurrentExecutor);
}
TaskExecutorAdapter adapter = new TaskExecutorAdapter(concurrentExecutor);
if (this.taskDecorator != null) {
adapter.setTaskDecorator(this.taskDecorator);
}
return adapter;
return new TaskExecutorAdapter(concurrentExecutor);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -100,7 +100,7 @@ public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements T
*/
public ConcurrentTaskScheduler() {
super();
initScheduledExecutor(null);
this.scheduledExecutor = initScheduledExecutor(null);
}
/**
@@ -115,7 +115,7 @@ public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements T
*/
public ConcurrentTaskScheduler(ScheduledExecutorService scheduledExecutor) {
super(scheduledExecutor);
initScheduledExecutor(scheduledExecutor);
this.scheduledExecutor = initScheduledExecutor(scheduledExecutor);
}
/**
@@ -131,11 +131,11 @@ public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements T
*/
public ConcurrentTaskScheduler(Executor concurrentExecutor, ScheduledExecutorService scheduledExecutor) {
super(concurrentExecutor);
initScheduledExecutor(scheduledExecutor);
this.scheduledExecutor = initScheduledExecutor(scheduledExecutor);
}
private void initScheduledExecutor(@Nullable ScheduledExecutorService scheduledExecutor) {
private ScheduledExecutorService initScheduledExecutor(@Nullable ScheduledExecutorService scheduledExecutor) {
if (scheduledExecutor != null) {
this.scheduledExecutor = scheduledExecutor;
this.enterpriseConcurrentScheduler = (managedScheduledExecutorServiceClass != null &&
@@ -145,6 +145,7 @@ public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements T
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
this.enterpriseConcurrentScheduler = false;
}
return this.scheduledExecutor;
}
/**
@@ -206,9 +207,9 @@ public class ConcurrentTaskScheduler extends ConcurrentTaskExecutor implements T
@Override
public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
long delay = startTime.getTime() - this.clock.millis();
long initialDelay = startTime.getTime() - this.clock.millis();
try {
return this.scheduledExecutor.schedule(decorateTask(task, false), delay, TimeUnit.MILLISECONDS);
return this.scheduledExecutor.schedule(decorateTask(task, false), initialDelay, TimeUnit.MILLISECONDS);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,10 +36,7 @@ import org.springframework.lang.Nullable;
* Base class for setting up a {@link java.util.concurrent.ExecutorService}
* (typically a {@link java.util.concurrent.ThreadPoolExecutor} or
* {@link java.util.concurrent.ScheduledThreadPoolExecutor}).
*
* <p>Defines common configuration settings and common lifecycle handling,
* inheriting thread customization options (name, priority, etc) from
* {@link org.springframework.util.CustomizableThreadCreator}.
* Defines common configuration settings and common lifecycle handling.
*
* @author Juergen Hoeller
* @since 3.0
@@ -108,9 +105,9 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac
/**
* Set whether to wait for scheduled tasks to complete on shutdown,
* not interrupting running tasks and executing all tasks in the queue.
* <p>Default is {@code false}, shutting down immediately through interrupting
* ongoing tasks and clearing the queue. Switch this flag to {@code true} if
* you prefer fully completed tasks at the expense of a longer shutdown phase.
* <p>Default is "false", shutting down immediately through interrupting
* ongoing tasks and clearing the queue. Switch this flag to "true" if you
* prefer fully completed tasks at the expense of a longer shutdown phase.
* <p>Note that Spring's container shutdown continues while ongoing tasks
* are being completed. If you want this executor to block and wait for the
* termination of tasks before the rest of the container continues to shut
@@ -202,7 +199,8 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac
/**
* Calls {@code shutdown} when the BeanFactory destroys the executor instance.
* Calls {@code shutdown} when the BeanFactory destroys
* the task executor instance.
* @see #shutdown()
*/
@Override
@@ -211,13 +209,9 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac
}
/**
* Perform a full shutdown on the underlying ExecutorService,
* according to the corresponding configuration settings.
* @see #setWaitForTasksToCompleteOnShutdown
* @see #setAwaitTerminationMillis
* Perform a shutdown on the underlying ExecutorService.
* @see java.util.concurrent.ExecutorService#shutdown()
* @see java.util.concurrent.ExecutorService#shutdownNow()
* @see java.util.concurrent.ExecutorService#awaitTermination
*/
public void shutdown() {
if (logger.isDebugEnabled()) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,8 +78,8 @@ class ReschedulingRunnable extends DelegatingErrorHandlingRunnable implements Sc
if (this.scheduledExecutionTime == null) {
return null;
}
long delay = this.scheduledExecutionTime.getTime() - this.triggerContext.getClock().millis();
this.currentFuture = this.executor.schedule(this, delay, TimeUnit.MILLISECONDS);
long initialDelay = this.scheduledExecutionTime.getTime() - this.triggerContext.getClock().millis();
this.currentFuture = this.executor.schedule(this, initialDelay, TimeUnit.MILLISECONDS);
return this;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -380,9 +380,9 @@ public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupport
@Override
public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
ScheduledExecutorService executor = getScheduledExecutor();
long delay = startTime.getTime() - this.clock.millis();
long initialDelay = startTime.getTime() - this.clock.millis();
try {
return executor.schedule(errorHandlingTask(task, false), delay, TimeUnit.MILLISECONDS);
return executor.schedule(errorHandlingTask(task, false), initialDelay, TimeUnit.MILLISECONDS);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -124,8 +124,6 @@ public class FieldError extends ObjectError {
@Override
public String toString() {
// We would preferably use ObjectUtils.nullSafeConciseToString(rejectedValue) here but
// keep including the full nullSafeToString representation for backwards compatibility.
return "Field error in object '" + getObjectName() + "' on field '" + this.field +
"': rejected value [" + ObjectUtils.nullSafeToString(this.rejectedValue) + "]; " +
resolvableToString();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -108,7 +108,7 @@ open class BeanDefinitionDsl internal constructor (private val init: BeanDefinit
SINGLETON,
/**
* Scope constant for the standard prototype scope
* Scope constant for the standard singleton scope
* @see org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE
*/
PROTOTYPE
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +28,6 @@ import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.aop.testfixture.advice.CountingBeforeAdvice;
import org.springframework.aop.testfixture.interceptor.NopInterceptor;
import org.springframework.beans.testfixture.beans.ITestBean;
@@ -36,8 +35,6 @@ import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -90,7 +87,8 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(new NopInterceptor());
AopProxy aop = createAopProxy(pc);
assertThatExceptionOfType(AopConfigException.class).isThrownBy(aop::getProxy);
assertThatExceptionOfType(AopConfigException.class).isThrownBy(
aop::getProxy);
}
@Test
@@ -138,8 +136,8 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
Object proxy = aop.getProxy();
assertThat(AopUtils.isCglibProxy(proxy)).isTrue();
assertThat(proxy).isInstanceOf(ITestBean.class);
assertThat(proxy).isInstanceOf(TestBean.class);
assertThat(proxy instanceof ITestBean).isTrue();
assertThat(proxy instanceof TestBean).isTrue();
TestBean tb = (TestBean) proxy;
assertThat(tb.getAge()).isEqualTo(32);
@@ -306,8 +304,6 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
CglibAopProxy cglib = new CglibAopProxy(as);
ITestBean proxy1 = (ITestBean) cglib.getProxy();
ITestBean proxy1a = (ITestBean) cglib.getProxy();
assertThat(proxy1a.getClass()).isSameAs(proxy1.getClass());
mockTargetSource.setTarget(proxy1);
as = new AdvisedSupport(new Class<?>[]{});
@@ -316,40 +312,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
cglib = new CglibAopProxy(as);
ITestBean proxy2 = (ITestBean) cglib.getProxy();
assertThat(proxy2).isInstanceOf(Serializable.class);
assertThat(proxy2.getClass()).isNotSameAs(proxy1.getClass());
ITestBean proxy2a = (ITestBean) cglib.getProxy();
assertThat(proxy2a).isInstanceOf(Serializable.class);
assertThat(proxy2a.getClass()).isSameAs(proxy2.getClass());
mockTargetSource.setTarget(proxy1);
as = new AdvisedSupport(new Class<?>[]{});
as.setTargetSource(mockTargetSource);
as.addAdvisor(new DefaultPointcutAdvisor(new AnnotationMatchingPointcut(Nullable.class), new NopInterceptor()));
cglib = new CglibAopProxy(as);
ITestBean proxy3 = (ITestBean) cglib.getProxy();
assertThat(proxy3).isInstanceOf(Serializable.class);
assertThat(proxy3.getClass()).isNotSameAs(proxy2.getClass());
ITestBean proxy3a = (ITestBean) cglib.getProxy();
assertThat(proxy3a).isInstanceOf(Serializable.class);
assertThat(proxy3a.getClass()).isSameAs(proxy3.getClass());
mockTargetSource.setTarget(proxy1);
as = new AdvisedSupport(new Class<?>[]{});
as.setTargetSource(mockTargetSource);
as.addAdvisor(new DefaultPointcutAdvisor(new AnnotationMatchingPointcut(NonNull.class), new NopInterceptor()));
cglib = new CglibAopProxy(as);
ITestBean proxy4 = (ITestBean) cglib.getProxy();
assertThat(proxy4).isInstanceOf(Serializable.class);
assertThat(proxy4.getClass()).isNotSameAs(proxy3.getClass());
ITestBean proxy4a = (ITestBean) cglib.getProxy();
assertThat(proxy4a).isInstanceOf(Serializable.class);
assertThat(proxy4a.getClass()).isSameAs(proxy4.getClass());
assertThat(proxy2 instanceof Serializable).isTrue();
}
@Test
@@ -368,7 +331,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
proxy.doTest();
}
catch (Exception ex) {
assertThat(ex).as("Invalid exception class").isInstanceOf(ApplicationContextException.class);
assertThat(ex instanceof ApplicationContextException).as("Invalid exception class").isTrue();
}
assertThat(proxy.isCatchInvoked()).as("Catch was not invoked").isTrue();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -207,9 +207,10 @@ public class ClassPathBeanDefinitionScannerTests {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
scanner.setIncludeAnnotationConfig(false);
scanner.scan("org.springframework.context.annotation3");
assertThatIllegalStateException().isThrownBy(() -> scanner.scan(BASE_PACKAGE))
.withMessageContaining("stubFooDao")
.withMessageContaining(StubFooDao.class.getName());
assertThatIllegalStateException().isThrownBy(() ->
scanner.scan(BASE_PACKAGE))
.withMessageContaining("stubFooDao")
.withMessageContaining(StubFooDao.class.getName());
}
@Test
@@ -266,10 +267,11 @@ public class ClassPathBeanDefinitionScannerTests {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
scanner.setIncludeAnnotationConfig(false);
scanner.scan("org.springframework.context.annotation2");
assertThatIllegalStateException().isThrownBy(() -> scanner.scan(BASE_PACKAGE))
.withMessageContaining("myNamedDao")
.withMessageContaining(NamedStubDao.class.getName())
.withMessageContaining(NamedStubDao2.class.getName());
assertThatIllegalStateException().isThrownBy(() ->
scanner.scan(BASE_PACKAGE))
.withMessageContaining("myNamedDao")
.withMessageContaining(NamedStubDao.class.getName())
.withMessageContaining(NamedStubDao2.class.getName());
}
@Test
@@ -79,7 +79,7 @@ class EnableLoadTimeWeavingTests {
@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.DISABLED)
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.DISABLED)
static class EnableLTWConfig_withAjWeavingDisabled implements LoadTimeWeavingConfigurer {
@Override
@@ -88,9 +88,8 @@ class EnableLoadTimeWeavingTests {
}
}
@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.AUTODETECT)
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.AUTODETECT)
static class EnableLTWConfig_withAjWeavingAutodetect implements LoadTimeWeavingConfigurer {
@Override
@@ -99,9 +98,8 @@ class EnableLoadTimeWeavingTests {
}
}
@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
static class EnableLTWConfig_withAjWeavingEnabled implements LoadTimeWeavingConfigurer {
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,7 +41,6 @@ class ImportTests {
private DefaultListableBeanFactory processConfigurationClasses(Class<?>... classes) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.setAllowBeanDefinitionOverriding(false);
for (Class<?> clazz : classes) {
beanFactory.registerBeanDefinition(clazz.getSimpleName(), new RootBeanDefinition(clazz));
}
@@ -57,9 +56,8 @@ class ImportTests {
for (Class<?> clazz : classes) {
beanFactory.getBean(clazz);
}
}
// ------------------------------------------------------------------------
}
@Test
void testProcessImportsWithAsm() {
@@ -160,13 +158,6 @@ class ImportTests {
assertBeanDefinitionCount(configClasses + beansInClasses, FirstLevel.class);
}
@Test
void testImportAnnotationWithThreeLevelRecursionAndDoubleImport() {
int configClasses = 5;
int beansInClasses = 5;
assertBeanDefinitionCount(configClasses + beansInClasses, FirstLevel.class, FirstLevelPlus.class);
}
// ------------------------------------------------------------------------
@Test
@@ -176,6 +167,7 @@ class ImportTests {
assertBeanDefinitionCount((configClasses + beansInClasses), WithMultipleArgumentsToImportAnnotation.class);
}
@Test
void testImportAnnotationWithMultipleArgumentsResultingInOverriddenBeanDefinition() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
@@ -253,11 +245,6 @@ class ImportTests {
}
}
@Configuration
@Import(ThirdLevel.class)
static class FirstLevelPlus {
}
@Configuration
@Import({ThirdLevel.class, InitBean.class})
static class SecondLevel {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.context.event;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -47,8 +46,6 @@ import static org.mockito.Mockito.verify;
/**
* @author Stephane Nicoll
* @author Juergen Hoeller
* @author Simon Baslé
*/
public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEventListenerTests {
@@ -83,23 +80,16 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
supportsEventType(false, method, ResolvableType.forClassWithGenerics(GenericTestEvent.class, Long.class));
}
@Test
public void genericListenerWithUnresolvedGenerics() {
Method method = ReflectionUtils.findMethod(
SampleEvents.class, "handleGenericString", GenericTestEvent.class);
supportsEventType(true, method, ResolvableType.forClass(GenericTestEvent.class));
}
@Test
public void listenerWithPayloadAndGenericInformation() {
Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
supportsEventType(true, method, createPayloadEventType(String.class));
supportsEventType(true, method, createGenericEventType(String.class));
}
@Test
public void listenerWithInvalidPayloadAndGenericInformation() {
Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
supportsEventType(false, method, createPayloadEventType(Integer.class));
supportsEventType(false, method, createGenericEventType(Integer.class));
}
@Test
@@ -123,28 +113,28 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
@Test
public void listenerWithAnnotationValue() {
Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringAnnotationValue");
supportsEventType(true, method, createPayloadEventType(String.class));
supportsEventType(true, method, createGenericEventType(String.class));
}
@Test
public void listenerWithAnnotationClasses() {
Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringAnnotationClasses");
supportsEventType(true, method, createPayloadEventType(String.class));
supportsEventType(true, method, createGenericEventType(String.class));
}
@Test
public void listenerWithAnnotationValueAndParameter() {
Method method = ReflectionUtils.findMethod(
SampleEvents.class, "handleStringAnnotationValueAndParameter", String.class);
supportsEventType(true, method, createPayloadEventType(String.class));
supportsEventType(true, method, createGenericEventType(String.class));
}
@Test
public void listenerWithSeveralTypes() {
Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringOrInteger");
supportsEventType(true, method, createPayloadEventType(String.class));
supportsEventType(true, method, createPayloadEventType(Integer.class));
supportsEventType(false, method, createPayloadEventType(Double.class));
supportsEventType(true, method, createGenericEventType(String.class));
supportsEventType(true, method, createGenericEventType(Integer.class));
supportsEventType(false, method, createGenericEventType(Double.class));
}
@Test
@@ -335,88 +325,6 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
verify(this.context, times(2)).getBean("testBean");
}
@Test // gh-30399
void simplePayloadDoesNotSupportArbitraryGenericEventType() throws Exception {
Method method = SampleEvents.class.getDeclaredMethod("handleString", String.class);
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClassWithGenerics(EntityWrapper.class, Integer.class))))
.as("handleString(String) with EntityWrapper<Integer>").isFalse();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClass(EntityWrapper.class))))
.as("handleString(String) with EntityWrapper<?>").isFalse();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClass(String.class))))
.as("handleString(String) with String").isTrue();
}
@Test // gh-30399
void genericPayloadDoesNotSupportArbitraryGenericEventType() throws Exception {
Method method = SampleEvents.class.getDeclaredMethod("handleGenericStringPayload", EntityWrapper.class);
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClass(EntityWrapper.class))))
.as("handleGenericStringPayload(EntityWrapper<String>) with EntityWrapper<?>").isFalse();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClassWithGenerics(EntityWrapper.class, Integer.class))))
.as("handleGenericStringPayload(EntityWrapper<String>) with EntityWrapper<Integer>").isFalse();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClassWithGenerics(EntityWrapper.class, String.class))))
.as("handleGenericStringPayload(EntityWrapper<String>) with EntityWrapper<String>").isTrue();
}
@Test // gh-30399
void rawGenericPayloadDoesNotSupportArbitraryGenericEventType() throws Exception {
Method method = SampleEvents.class.getDeclaredMethod("handleGenericAnyPayload", EntityWrapper.class);
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClass(EntityWrapper.class))))
.as("handleGenericAnyPayload(EntityWrapper<?>) with EntityWrapper<?>").isTrue();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClassWithGenerics(EntityWrapper.class, Integer.class))))
.as("handleGenericAnyPayload(EntityWrapper<?>) with EntityWrapper<Integer>").isTrue();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClassWithGenerics(EntityWrapper.class, String.class))))
.as("handleGenericAnyPayload(EntityWrapper<?>) with EntityWrapper<String>").isTrue();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClass(List.class))))
.as("handleGenericAnyPayload(EntityWrapper<?>) with List<?>").isFalse();
assertThat(adapter.supportsEventType(createPayloadEventType(ResolvableType.forClassWithGenerics(List.class, String.class))))
.as("handleGenericAnyPayload(EntityWrapper<?>) with List<String>").isFalse();
}
@Test // gh-30399
void genericApplicationEventSupportsSpecificType() throws Exception {
Method method = SampleEvents.class.getDeclaredMethod("handleGenericString", GenericTestEvent.class);
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
assertThat(adapter.supportsEventType(ResolvableType.forClass(GenericTestEvent.class)))
.as("handleGenericString(GenericTestEvent<String>) with GenericTestEvent<?>").isTrue();
assertThat(adapter.supportsEventType(ResolvableType.forClassWithGenerics(GenericTestEvent.class, Integer.class)))
.as("handleGenericString(GenericTestEvent<String>) with GenericTestEvent<Integer>").isFalse();
assertThat(adapter.supportsEventType(ResolvableType.forClassWithGenerics(GenericTestEvent.class, String.class)))
.as("handleGenericString(GenericTestEvent<String>) with GenericTestEvent<String>").isTrue();
}
@Test // gh-30399
void genericRawApplicationEventSupportsRawTypeAndAnySpecificType() throws Exception {
Method method = SampleEvents.class.getDeclaredMethod("handleGenericRaw", GenericTestEvent.class);
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
assertThat(adapter.supportsEventType(ResolvableType.forClass(GenericTestEvent.class)))
.as("handleGenericRaw(GenericTestEvent<?>) with GenericTestEvent<?>").isTrue();
assertThat(adapter.supportsEventType(ResolvableType.forClassWithGenerics(GenericTestEvent.class, String.class)))
.as("handleGenericRaw(GenericTestEvent<?>) with GenericTestEvent<String>").isTrue();
assertThat(adapter.supportsEventType(ResolvableType.forClassWithGenerics(GenericTestEvent.class, Integer.class)))
.as("handleGenericRaw(GenericTestEvent<?>) with GenericTestEvent<Integer>").isTrue();
}
@Test // gh-30399
void unrelatedApplicationEventDoesNotSupportRawTypeOrAnySpecificType() throws Exception {
Method method = SampleEvents.class.getDeclaredMethod("handleUnrelated", ContextRefreshedEvent.class);
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
assertThat(adapter.supportsEventType(ResolvableType.forClass(GenericTestEvent.class)))
.as("handleUnrelated(ContextRefreshedEvent) with GenericTestEvent<?>").isTrue(); // known bug in 5.3.x
assertThat(adapter.supportsEventType(ResolvableType.forClassWithGenerics(GenericTestEvent.class, String.class)))
.as("handleUnrelated(ContextRefreshedEvent) with GenericTestEvent<String>").isFalse();
assertThat(adapter.supportsEventType(ResolvableType.forClassWithGenerics(GenericTestEvent.class, Integer.class)))
.as("handleUnrelated(ContextRefreshedEvent) with GenericTestEvent<Integer>").isFalse();
}
private void supportsEventType(boolean match, Method method, ResolvableType eventType) {
ApplicationListenerMethodAdapter adapter = createTestInstance(method);
@@ -433,11 +341,7 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
return new StaticApplicationListenerMethodAdapter(method, this.sampleEvents);
}
private ResolvableType createPayloadEventType(Class<?> payloadType) {
return ResolvableType.forClassWithGenerics(PayloadApplicationEvent.class, payloadType);
}
private ResolvableType createPayloadEventType(ResolvableType payloadType) {
private ResolvableType createGenericEventType(Class<?> payloadType) {
return ResolvableType.forClassWithGenerics(PayloadApplicationEvent.class, payloadType);
}
@@ -469,14 +373,6 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
public void handleGenericString(GenericTestEvent<String> event) {
}
@EventListener
public void handleGenericRaw(GenericTestEvent<?> event) {
}
@EventListener
public void handleUnrelated(ContextRefreshedEvent event) {
}
@EventListener
public void handleString(String payload) {
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -133,7 +133,7 @@ public class DateFormattingTests {
assertThat(exception)
.hasMessageContaining("for property 'styleDate'")
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value [99/01/01]")
.hasMessageContaining("for value '99/01/01'")
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [99/01/01]")
.hasCauseInstanceOf(ParseException.class).cause()
@@ -353,7 +353,7 @@ public class DateFormattingTests {
assertThat(fieldError.unwrap(TypeMismatchException.class))
.hasMessageContaining("for property 'patternDateWithFallbackPatterns'")
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value [210302]")
.hasMessageContaining("for value '210302'")
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [210302]")
.hasCauseInstanceOf(ParseException.class).cause()
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -333,7 +333,7 @@ class DateTimeFormattingTests {
assertThat(fieldError.unwrap(TypeMismatchException.class))
.hasMessageContaining("for property 'isoLocalDate'")
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value [2009-31-10]")
.hasMessageContaining("for value '2009-31-10'")
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [2009-31-10]")
.hasCauseInstanceOf(DateTimeParseException.class).cause()
@@ -540,7 +540,7 @@ class DateTimeFormattingTests {
assertThat(fieldError.unwrap(TypeMismatchException.class))
.hasMessageContaining("for property 'patternLocalDateWithFallbackPatterns'")
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value [210302]")
.hasMessageContaining("for value '210302'")
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [210302]")
.hasCauseInstanceOf(DateTimeParseException.class).cause()
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -85,13 +85,16 @@ public class ReflectiveLoadTimeWeaverTests {
private int numTimesAddTransformerCalled = 0;
public int getNumTimesGetThrowawayClassLoaderCalled() {
return this.numTimesAddTransformerCalled;
}
public void addTransformer(ClassFileTransformer transformer) {
++this.numTimesAddTransformerCalled;
}
}
@@ -99,15 +102,18 @@ public class ReflectiveLoadTimeWeaverTests {
private int numTimesGetThrowawayClassLoaderCalled = 0;
@Override
public int getNumTimesGetThrowawayClassLoaderCalled() {
return this.numTimesGetThrowawayClassLoaderCalled;
}
public ClassLoader getThrowawayClassLoader() {
++this.numTimesGetThrowawayClassLoaderCalled;
return getClass().getClassLoader();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -95,8 +95,9 @@ public class EnableAsyncTests {
public void properExceptionForExistingProxyDependencyMismatch() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AsyncConfig.class, AsyncBeanWithInterface.class, AsyncBeanUser.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(ctx::refresh)
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
ctx::refresh)
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
ctx.close();
}
@@ -104,8 +105,9 @@ public class EnableAsyncTests {
public void properExceptionForResolvedProxyDependencyMismatch() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AsyncConfig.class, AsyncBeanUser.class, AsyncBeanWithInterface.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(ctx::refresh)
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
ctx::refresh)
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
ctx.close();
}
@@ -180,7 +182,8 @@ public class EnableAsyncTests {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AspectJAsyncAnnotationConfig.class);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(ctx::refresh);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(
ctx::refresh);
}
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,7 +61,7 @@ public class EnableSchedulingTests {
@EnabledForTestGroups(LONG_RUNNING)
public void withFixedRateTask() throws InterruptedException {
ctx = new AnnotationConfigApplicationContext(FixedRateTaskConfig.class);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks()).hasSize(2);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(2);
Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
@@ -71,7 +71,7 @@ public class EnableSchedulingTests {
@EnabledForTestGroups(LONG_RUNNING)
public void withSubclass() throws InterruptedException {
ctx = new AnnotationConfigApplicationContext(FixedRateTaskConfigSubclass.class);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks()).hasSize(2);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(2);
Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
@@ -81,13 +81,13 @@ public class EnableSchedulingTests {
@EnabledForTestGroups(LONG_RUNNING)
public void withExplicitScheduler() throws InterruptedException {
ctx = new AnnotationConfigApplicationContext(ExplicitSchedulerConfig.class);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks()).hasSize(1);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(1);
Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
assertThat(ctx.getBean(ExplicitSchedulerConfig.class).threadName).startsWith("explicitScheduler-");
assertThat(Arrays.asList(ctx.getDefaultListableBeanFactory().getDependentBeans("myTaskScheduler")).contains(
TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue();
TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue();
}
@Test
@@ -100,7 +100,7 @@ public class EnableSchedulingTests {
@EnabledForTestGroups(LONG_RUNNING)
public void withExplicitScheduledTaskRegistrar() throws InterruptedException {
ctx = new AnnotationConfigApplicationContext(ExplicitScheduledTaskRegistrarConfig.class);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks()).hasSize(1);
assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(1);
Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
@BeforeEach
void setup(TestInfo testInfo) {
void setUp(TestInfo testInfo) {
this.testName = testInfo.getTestMethod().get().getName();
this.threadNamePrefix = this.testName + "-";
this.executor = buildExecutor();
@@ -84,11 +84,11 @@ abstract class AbstractSchedulingTaskExecutorTests {
TestTask task = new TestTask(this.testName, 0);
executor.execute(task);
Awaitility.await()
.dontCatchUncaughtExceptions()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> task.exception.get() != null && task.exception.get().getMessage().equals(
"TestTask failure for test 'executeFailingRunnable': expectedRunCount:<0>, actualRunCount:<1>"));
.dontCatchUncaughtExceptions()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> task.exception.get() != null && task.exception.get().getMessage().equals(
"TestTask failure for test 'executeFailingRunnable': expectedRunCount:<0>, actualRunCount:<1>"));
}
@Test
@@ -101,7 +101,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
void submitFailingRunnable() {
void submitFailingRunnable() throws Exception {
TestTask task = new TestTask(this.testName, 0);
Future<?> future = executor.submit(task);
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
@@ -121,31 +121,31 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
void submitListenableRunnable() {
void submitListenableRunnable() throws Exception {
TestTask task = new TestTask(this.testName, 1);
// Act
ListenableFuture<?> future = executor.submitListenable(task);
future.addCallback(result -> outcome = result, ex -> outcome = ex);
// Assert
Awaitility.await()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(future::isDone);
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(future::isDone);
assertThat(outcome).isNull();
assertThreadNamePrefix(task);
}
@Test
void submitFailingListenableRunnable() {
void submitFailingListenableRunnable() throws Exception {
TestTask task = new TestTask(this.testName, 0);
ListenableFuture<?> future = executor.submitListenable(task);
future.addCallback(result -> outcome = result, ex -> outcome = ex);
Awaitility.await()
.dontCatchUncaughtExceptions()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> future.isDone() && outcome != null);
.dontCatchUncaughtExceptions()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> future.isDone() && outcome != null);
assertThat(outcome.getClass()).isSameAs(RuntimeException.class);
}
@@ -159,13 +159,14 @@ abstract class AbstractSchedulingTaskExecutorTests {
future1.get(1000, TimeUnit.MILLISECONDS);
}
catch (Exception ex) {
// ignore
/* ignore */
}
Awaitility.await()
.atMost(4, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.untilAsserted(() -> assertThatExceptionOfType(CancellationException.class)
.isThrownBy(() -> future2.get(1000, TimeUnit.MILLISECONDS)));
.atMost(4, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.untilAsserted(() ->
assertThatExceptionOfType(CancellationException.class).isThrownBy(() ->
future2.get(1000, TimeUnit.MILLISECONDS)));
}
@Test
@@ -177,11 +178,11 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
void submitFailingCallable() {
void submitFailingCallable() throws Exception {
TestCallable task = new TestCallable(this.testName, 0);
Future<String> future = executor.submit(task);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> future.get(1000, TimeUnit.MILLISECONDS));
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
future.get(1000, TimeUnit.MILLISECONDS));
assertThat(future.isDone()).isTrue();
}
@@ -195,41 +196,42 @@ abstract class AbstractSchedulingTaskExecutorTests {
future1.get(1000, TimeUnit.MILLISECONDS);
}
catch (Exception ex) {
// ignore
/* ignore */
}
Awaitility.await()
.atMost(4, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.untilAsserted(() -> assertThatExceptionOfType(CancellationException.class)
.isThrownBy(() -> future2.get(1000, TimeUnit.MILLISECONDS)));
.atMost(4, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.untilAsserted(() ->
assertThatExceptionOfType(CancellationException.class).isThrownBy(() ->
future2.get(1000, TimeUnit.MILLISECONDS)));
}
@Test
void submitListenableCallable() {
void submitListenableCallable() throws Exception {
TestCallable task = new TestCallable(this.testName, 1);
// Act
ListenableFuture<String> future = executor.submitListenable(task);
future.addCallback(result -> outcome = result, ex -> outcome = ex);
// Assert
Awaitility.await()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> future.isDone() && outcome != null);
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> future.isDone() && outcome != null);
assertThat(outcome.toString().substring(0, this.threadNamePrefix.length())).isEqualTo(this.threadNamePrefix);
}
@Test
void submitFailingListenableCallable() {
void submitFailingListenableCallable() throws Exception {
TestCallable task = new TestCallable(this.testName, 0);
// Act
ListenableFuture<String> future = executor.submitListenable(task);
future.addCallback(result -> outcome = result, ex -> outcome = ex);
// Assert
Awaitility.await()
.dontCatchUncaughtExceptions()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> future.isDone() && outcome != null);
.dontCatchUncaughtExceptions()
.atMost(1, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> future.isDone() && outcome != null);
assertThat(outcome.getClass()).isSameAs(RuntimeException.class);
}
@@ -294,9 +296,8 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
if (expectedRunCount >= 0) {
if (actualRunCount.incrementAndGet() > expectedRunCount) {
RuntimeException exception = new RuntimeException(String.format(
"%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>",
getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get()));
RuntimeException exception = new RuntimeException(String.format("%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>",
getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get()));
this.exception.set(exception);
throw exception;
}
@@ -328,9 +329,8 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
if (expectedRunCount >= 0) {
if (actualRunCount.incrementAndGet() > expectedRunCount) {
throw new RuntimeException(String.format(
"%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>",
getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get()));
throw new RuntimeException(String.format("%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>",
getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get()));
}
}
return Thread.currentThread().getName();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.scheduling.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ThreadPoolExecutor;
@@ -27,8 +26,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.task.AsyncListenableTaskExecutor;
import org.springframework.core.task.NoOpRunnable;
import org.springframework.core.task.TaskDecorator;
import org.springframework.util.Assert;
import static org.assertj.core.api.Assertions.assertThatCode;
@@ -72,45 +69,10 @@ class ConcurrentTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
}
@Test
void earlySetConcurrentExecutorCallRespectsConfiguredTaskDecorator() {
void passingNullExecutorToSetterResultsInDefaultTaskExecutorBeingUsed() {
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
executor.setConcurrentExecutor(new DecoratedExecutor());
executor.setTaskDecorator(new RunnableDecorator());
executor.setConcurrentExecutor(null);
assertThatCode(() -> executor.execute(new NoOpRunnable())).doesNotThrowAnyException();
}
@Test
void lateSetConcurrentExecutorCallRespectsConfiguredTaskDecorator() {
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
executor.setTaskDecorator(new RunnableDecorator());
executor.setConcurrentExecutor(new DecoratedExecutor());
assertThatCode(() -> executor.execute(new NoOpRunnable())).doesNotThrowAnyException();
}
private static class DecoratedRunnable implements Runnable {
@Override
public void run() {
}
}
private static class RunnableDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
return new DecoratedRunnable();
}
}
private static class DecoratedExecutor implements Executor {
@Override
public void execute(Runnable command) {
Assert.state(command instanceof DecoratedRunnable, "TaskDecorator not applied");
}
}
}
@@ -41,14 +41,14 @@ import static org.springframework.core.testfixture.TestGroup.LONG_RUNNING;
class ScheduledExecutorFactoryBeanTests {
@Test
void throwsExceptionIfPoolSizeIsLessThanZero() {
void throwsExceptionIfPoolSizeIsLessThanZero() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertThatIllegalArgumentException().isThrownBy(() -> factory.setPoolSize(-1));
}
@Test
@SuppressWarnings("serial")
void shutdownNowIsPropagatedToTheExecutorOnDestroy() {
void shutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
@@ -66,7 +66,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@SuppressWarnings("serial")
void shutdownIsPropagatedToTheExecutorOnDestroy() {
void shutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
@@ -85,7 +85,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
void oneTimeExecutionIsSetUpAndFiresCorrectly() {
void oneTimeExecutionIsSetUpAndFiresCorrectly() throws Exception {
Runnable runnable = mock(Runnable.class);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
@@ -99,7 +99,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
void fixedRepeatedExecutionIsSetUpAndFiresCorrectly() {
void fixedRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
Runnable runnable = mock(Runnable.class);
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
@@ -117,7 +117,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
void fixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() {
void fixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
Runnable runnable = mock(Runnable.class);
willThrow(new IllegalStateException()).given(runnable).run();
@@ -137,7 +137,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
void withInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() {
void withInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
Runnable runnable = mock(Runnable.class);
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
@@ -157,7 +157,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
void withInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() {
void withInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
Runnable runnable = mock(Runnable.class);
willThrow(new IllegalStateException()).given(runnable).run();
@@ -179,7 +179,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@SuppressWarnings("serial")
void settingThreadFactoryToNullForcesUseOfDefaultButIsOtherwiseCool() {
void settingThreadFactoryToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
@Override
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
@@ -195,7 +195,7 @@ class ScheduledExecutorFactoryBeanTests {
@Test
@SuppressWarnings("serial")
void settingRejectedExecutionHandlerToNullForcesUseOfDefaultButIsOtherwiseCool() {
void settingRejectedExecutionHandlerToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
@Override
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
@@ -210,7 +210,7 @@ class ScheduledExecutorFactoryBeanTests {
}
@Test
void objectTypeReportsCorrectType() {
void objectTypeReportsCorrectType() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertThat(factory.getObjectType()).isEqualTo(ScheduledExecutorService.class);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,8 +26,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.task.AsyncListenableTaskExecutor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.InstanceOfAssertFactories.type;
/**
@@ -67,7 +67,8 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
assertThat(executor.getCorePoolSize()).isEqualTo(1);
assertThat(executor.getThreadPoolExecutor().getCorePoolSize()).isEqualTo(1);
assertThatIllegalArgumentException().isThrownBy(() -> executor.setCorePoolSize(-1));
assertThatThrownBy(() -> executor.setCorePoolSize(-1))
.isInstanceOf(IllegalArgumentException.class);
assertThat(executor.getCorePoolSize()).isEqualTo(1);
assertThat(executor.getThreadPoolExecutor().getCorePoolSize()).isEqualTo(1);
@@ -89,7 +90,8 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
assertThat(executor.getMaxPoolSize()).isEqualTo(1);
assertThat(executor.getThreadPoolExecutor().getMaximumPoolSize()).isEqualTo(1);
assertThatIllegalArgumentException().isThrownBy(() -> executor.setMaxPoolSize(0));
assertThatThrownBy(() -> executor.setMaxPoolSize(0))
.isInstanceOf(IllegalArgumentException.class);
assertThat(executor.getMaxPoolSize()).isEqualTo(1);
assertThat(executor.getThreadPoolExecutor().getMaximumPoolSize()).isEqualTo(1);
@@ -111,7 +113,8 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
assertThat(executor.getKeepAliveSeconds()).isEqualTo(60);
assertThat(executor.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS)).isEqualTo(60);
assertThatIllegalArgumentException().isThrownBy(() -> executor.setKeepAliveSeconds(-10));
assertThatThrownBy(() -> executor.setKeepAliveSeconds(-10))
.isInstanceOf(IllegalArgumentException.class);
assertThat(executor.getKeepAliveSeconds()).isEqualTo(60);
assertThat(executor.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS)).isEqualTo(60);
@@ -121,8 +124,8 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
void queueCapacityDefault() {
assertThat(executor.getQueueCapacity()).isEqualTo(Integer.MAX_VALUE);
assertThat(executor.getThreadPoolExecutor().getQueue())
.asInstanceOf(type(LinkedBlockingQueue.class))
.extracting(BlockingQueue::remainingCapacity).isEqualTo(Integer.MAX_VALUE);
.asInstanceOf(type(LinkedBlockingQueue.class))
.extracting(BlockingQueue::remainingCapacity).isEqualTo(Integer.MAX_VALUE);
}
@Test
@@ -132,8 +135,8 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
assertThat(executor.getQueueCapacity()).isZero();
assertThat(executor.getThreadPoolExecutor().getQueue())
.asInstanceOf(type(SynchronousQueue.class))
.extracting(BlockingQueue::remainingCapacity).isEqualTo(0);
.asInstanceOf(type(SynchronousQueue.class))
.extracting(BlockingQueue::remainingCapacity).isEqualTo(0);
}
@Test
@@ -576,17 +576,15 @@ public class ReflectUtils {
c = (Class) lookupDefineClassMethod.invoke(lookup, b);
}
catch (InvocationTargetException ex) {
Throwable target = ex.getTargetException();
if (target.getClass() != LinkageError.class && target.getClass() != IllegalAccessException.class) {
throw new CodeGenerationException(target);
}
throw new CodeGenerationException(target) {
throw new CodeGenerationException(ex.getTargetException());
}
catch (IllegalAccessException ex) {
throw new CodeGenerationException(ex) {
@Override
public String getMessage() {
return "ClassLoader mismatch for [" + contextClass.getName() +
"]: JVM should be started with --add-opens=java.base/java.lang=ALL-UNNAMED " +
"for ClassLoader.defineClass to be accessible on " + loader.getClass().getName() +
"; consider co-locating the affected class in that target ClassLoader instead.";
"for ClassLoader.defineClass to be accessible on " + loader.getClass().getName();
}
};
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,7 +68,6 @@ public final class CollectionFactory {
approximableCollectionTypes.add(SortedSet.class);
approximableCollectionTypes.add(NavigableSet.class);
approximableMapTypes.add(Map.class);
approximableMapTypes.add(MultiValueMap.class);
approximableMapTypes.add(SortedMap.class);
approximableMapTypes.add(NavigableMap.class);
@@ -81,7 +80,6 @@ public final class CollectionFactory {
approximableCollectionTypes.add(EnumSet.class);
approximableMapTypes.add(HashMap.class);
approximableMapTypes.add(LinkedHashMap.class);
approximableMapTypes.add(LinkedMultiValueMap.class);
approximableMapTypes.add(TreeMap.class);
approximableMapTypes.add(EnumMap.class);
}
@@ -123,7 +121,13 @@ public final class CollectionFactory {
*/
@SuppressWarnings({"rawtypes", "unchecked", "cast"})
public static <E> Collection<E> createApproximateCollection(@Nullable Object collection, int capacity) {
if (collection instanceof EnumSet) {
if (collection instanceof LinkedList) {
return new LinkedList<>();
}
else if (collection instanceof List) {
return new ArrayList<>(capacity);
}
else if (collection instanceof EnumSet) {
// Cast is necessary for compilation in Eclipse 4.4.1.
Collection<E> enumSet = (Collection<E>) EnumSet.copyOf((EnumSet) collection);
enumSet.clear();
@@ -132,12 +136,6 @@ public final class CollectionFactory {
else if (collection instanceof SortedSet) {
return new TreeSet<>(((SortedSet<E>) collection).comparator());
}
if (collection instanceof LinkedList) {
return new LinkedList<>();
}
else if (collection instanceof List) {
return new ArrayList<>(capacity);
}
else {
return new LinkedHashSet<>(capacity);
}
@@ -183,7 +181,7 @@ public final class CollectionFactory {
@SuppressWarnings({"unchecked", "cast"})
public static <E> Collection<E> createCollection(Class<?> collectionType, @Nullable Class<?> elementType, int capacity) {
Assert.notNull(collectionType, "Collection type must not be null");
if (LinkedHashSet.class == collectionType ||
if (LinkedHashSet.class == collectionType || HashSet.class == collectionType ||
Set.class == collectionType || Collection.class == collectionType) {
return new LinkedHashSet<>(capacity);
}
@@ -193,8 +191,8 @@ public final class CollectionFactory {
else if (LinkedList.class == collectionType) {
return new LinkedList<>();
}
else if (TreeSet.class == collectionType || NavigableSet.class == collectionType ||
SortedSet.class == collectionType) {
else if (TreeSet.class == collectionType || NavigableSet.class == collectionType
|| SortedSet.class == collectionType) {
return new TreeSet<>();
}
else if (EnumSet.class.isAssignableFrom(collectionType)) {
@@ -202,9 +200,6 @@ public final class CollectionFactory {
// Cast is necessary for compilation in Eclipse 4.4.1.
return (Collection<E>) EnumSet.noneOf(asEnumType(elementType));
}
else if (HashSet.class == collectionType) {
return new HashSet<>(capacity);
}
else {
if (collectionType.isInterface() || !Collection.class.isAssignableFrom(collectionType)) {
throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName());
@@ -256,9 +251,6 @@ public final class CollectionFactory {
else if (map instanceof SortedMap) {
return new TreeMap<>(((SortedMap<K, V>) map).comparator());
}
else if (map instanceof MultiValueMap) {
return new LinkedMultiValueMap(capacity);
}
else {
return new LinkedHashMap<>(capacity);
}
@@ -305,24 +297,26 @@ public final class CollectionFactory {
@SuppressWarnings({"rawtypes", "unchecked"})
public static <K, V> Map<K, V> createMap(Class<?> mapType, @Nullable Class<?> keyType, int capacity) {
Assert.notNull(mapType, "Map type must not be null");
if (LinkedHashMap.class == mapType || Map.class == mapType) {
return new LinkedHashMap<>(capacity);
}
else if (LinkedMultiValueMap.class == mapType || MultiValueMap.class == mapType) {
return new LinkedMultiValueMap();
}
else if (TreeMap.class == mapType || SortedMap.class == mapType || NavigableMap.class == mapType) {
return new TreeMap<>();
if (mapType.isInterface()) {
if (Map.class == mapType) {
return new LinkedHashMap<>(capacity);
}
else if (SortedMap.class == mapType || NavigableMap.class == mapType) {
return new TreeMap<>();
}
else if (MultiValueMap.class == mapType) {
return new LinkedMultiValueMap();
}
else {
throw new IllegalArgumentException("Unsupported Map interface: " + mapType.getName());
}
}
else if (EnumMap.class == mapType) {
Assert.notNull(keyType, "Cannot create EnumMap for unknown key type");
return new EnumMap(asEnumType(keyType));
}
else if (HashMap.class == mapType) {
return new HashMap<>(capacity);
}
else {
if (mapType.isInterface() || !Map.class.isAssignableFrom(mapType)) {
if (!Map.class.isAssignableFrom(mapType)) {
throw new IllegalArgumentException("Unsupported Map type: " + mapType.getName());
}
try {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -781,7 +781,6 @@ public class MethodParameter {
return new MethodParameter(this);
}
/**
* Create a new MethodParameter for the given method or constructor.
* <p>This is a convenience factory method for scenarios where a
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -133,9 +133,6 @@ public class ResolvableType implements Serializable {
@Nullable
private volatile ResolvableType[] generics;
@Nullable
private volatile Boolean unresolvableGenerics;
/**
* Private constructor used to create a new {@link ResolvableType} for cache key purposes,
@@ -548,15 +545,6 @@ public class ResolvableType implements Serializable {
if (this == NONE) {
return false;
}
Boolean unresolvableGenerics = this.unresolvableGenerics;
if (unresolvableGenerics == null) {
unresolvableGenerics = determineUnresolvableGenerics();
this.unresolvableGenerics = unresolvableGenerics;
}
return unresolvableGenerics;
}
private boolean determineUnresolvableGenerics() {
ResolvableType[] generics = getGenerics();
for (ResolvableType generic : generics) {
if (generic.isUnresolvableTypeVariable() || generic.isWildcardWithoutBounds()) {
@@ -568,7 +556,7 @@ public class ResolvableType implements Serializable {
try {
for (Type genericInterface : resolved.getGenericInterfaces()) {
if (genericInterface instanceof Class) {
if (((Class<?>) genericInterface).getTypeParameters().length > 0) {
if (forClass((Class<?>) genericInterface).hasGenerics()) {
return true;
}
}
@@ -577,10 +565,7 @@ public class ResolvableType implements Serializable {
catch (TypeNotPresentException ex) {
// Ignore non-present types in generic signature
}
Class<?> superclass = resolved.getSuperclass();
if (superclass != null && superclass != Object.class) {
return getSuperType().hasUnresolvableGenerics();
}
return getSuperType().hasUnresolvableGenerics();
}
return false;
}
@@ -22,6 +22,7 @@ import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
@@ -203,18 +204,19 @@ final class SerializableTypeWrapper {
return forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, -1));
}
else if (Type[].class == method.getReturnType() && ObjectUtils.isEmpty(args)) {
Object returnValue = ReflectionUtils.invokeMethod(method, this.provider.getType());
if (returnValue == null) {
return null;
}
Type[] result = new Type[((Type[]) returnValue).length];
Type[] result = new Type[((Type[]) method.invoke(this.provider.getType())).length];
for (int i = 0; i < result.length; i++) {
result[i] = forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, i));
}
return result;
}
return ReflectionUtils.invokeMethod(method, this.provider.getType(), args);
try {
return method.invoke(this.provider.getType(), args);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -149,8 +149,8 @@ public abstract class AnnotationUtils {
* @since 5.2
* @see #isCandidateClass(Class, String)
*/
public static boolean isCandidateClass(Class<?> clazz, @Nullable Class<? extends Annotation> annotationType) {
return (annotationType != null && isCandidateClass(clazz, annotationType.getName()));
public static boolean isCandidateClass(Class<?> clazz, Class<? extends Annotation> annotationType) {
return isCandidateClass(clazz, annotationType.getName());
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ public class ConversionFailedException extends ConversionException {
@Nullable Object value, Throwable cause) {
super("Failed to convert from type [" + sourceType + "] to type [" + targetType +
"] for value [" + ObjectUtils.nullSafeConciseToString(value) + "]", cause);
"] for value '" + ObjectUtils.nullSafeToString(value) + "'", cause);
this.sourceType = sourceType;
this.targetType = targetType;
this.value = value;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,8 +57,6 @@ package org.springframework.core.env;
* of property sources prior to application context {@code refresh()}.
*
* @author Chris Beams
* @author Phillip Webb
* @author Sam Brannen
* @since 3.1
* @see PropertyResolver
* @see EnvironmentCapable
@@ -97,56 +95,25 @@ public interface Environment extends PropertyResolver {
String[] getDefaultProfiles();
/**
* Determine whether one of the given profile expressions matches the
* {@linkplain #getActiveProfiles() active profiles} &mdash; or in the case
* of no explicit active profiles, whether one of the given profile expressions
* matches the {@linkplain #getDefaultProfiles() default profiles}.
* <p>Profile expressions allow for complex, boolean profile logic to be
* expressed &mdash; for example {@code "p1 & p2"}, {@code "(p1 & p2) | p3"},
* etc. See {@link Profiles#of(String...)} for details on the supported
* expression syntax.
* <p>This method is a convenient shortcut for
* {@code env.acceptsProfiles(Profiles.of(profileExpressions))}.
* @since 5.3.28
* @see Profiles#of(String...)
* @see #acceptsProfiles(Profiles)
*/
default boolean matchesProfiles(String... profileExpressions) {
return acceptsProfiles(Profiles.of(profileExpressions));
}
/**
* Determine whether one or more of the given profiles is active &mdash; or
* in the case of no explicit {@linkplain #getActiveProfiles() active profiles},
* whether one or more of the given profiles is included in the set of
* {@linkplain #getDefaultProfiles() default profiles}.
* <p>If a profile begins with '!' the logic is inverted, meaning this method
* will return {@code true} if the given profile is <em>not</em> active. For
* example, {@code env.acceptsProfiles("p1", "!p2")} will return {@code true}
* if profile 'p1' is active or 'p2' is not active.
* @throws IllegalArgumentException if called with a {@code null} array, an
* empty array, zero arguments or if any profile is {@code null}, empty, or
* whitespace only
* Return whether one or more of the given profiles is active or, in the case of no
* explicit active profiles, whether one or more of the given profiles is included in
* the set of default profiles. If a profile begins with '!' the logic is inverted,
* i.e. the method will return {@code true} if the given profile is <em>not</em> active.
* For example, {@code env.acceptsProfiles("p1", "!p2")} will return {@code true} if
* profile 'p1' is active or 'p2' is not active.
* @throws IllegalArgumentException if called with zero arguments
* or if any profile is {@code null}, empty, or whitespace only
* @see #getActiveProfiles
* @see #getDefaultProfiles
* @see #matchesProfiles(String...)
* @see #acceptsProfiles(Profiles)
* @deprecated as of 5.1 in favor of {@link #acceptsProfiles(Profiles)} or
* {@link #matchesProfiles(String...)}
* @deprecated as of 5.1 in favor of {@link #acceptsProfiles(Profiles)}
*/
@Deprecated
boolean acceptsProfiles(String... profiles);
/**
* Determine whether the given {@link Profiles} predicate matches the
* {@linkplain #getActiveProfiles() active profiles} &mdash; or in the case
* of no explicit active profiles, whether the given {@code Profiles} predicate
* matches the {@linkplain #getDefaultProfiles() default profiles}.
* <p>If you wish provide profile expressions directly as strings, use
* {@link #matchesProfiles(String...)} instead.
* @since 5.1
* @see #matchesProfiles(String...)
* @see Profiles#of(String...)
* Return whether the {@linkplain #getActiveProfiles() active profiles}
* match the given {@link Profiles} predicate.
*/
boolean acceptsProfiles(Profiles profiles);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,32 +43,32 @@ public interface Profiles {
/**
* Create a new {@link Profiles} instance that checks for matches against
* the given <em>profile expressions</em>.
* the given <em>profile strings</em>.
* <p>The returned instance will {@linkplain Profiles#matches(Predicate) match}
* if any one of the given profile expressions matches.
* <p>A profile expression may contain a simple profile name (for example
* {@code "production"}) or a compound expression. A compound expression allows
* if any one of the given profile strings matches.
* <p>A profile string may contain a simple profile name (for example
* {@code "production"}) or a profile expression. A profile expression allows
* for more complicated profile logic to be expressed, for example
* {@code "production & cloud"}.
* <p>The following operators are supported in profile expressions.
* <ul>
* <li>{@code !} - A logical <em>NOT</em> of the profile name or compound expression</li>
* <li>{@code &} - A logical <em>AND</em> of the profile names or compound expressions</li>
* <li>{@code |} - A logical <em>OR</em> of the profile names or compound expressions</li>
* <li>{@code !} - A logical <em>NOT</em> of the profile or profile expression</li>
* <li>{@code &} - A logical <em>AND</em> of the profiles or profile expressions</li>
* <li>{@code |} - A logical <em>OR</em> of the profiles or profile expressions</li>
* </ul>
* <p>Please note that the {@code &} and {@code |} operators may not be mixed
* without using parentheses. For example, {@code "a & b | c"} is not a valid
* expression: it must be expressed as {@code "(a & b) | c"} or
* without using parentheses. For example {@code "a & b | c"} is not a valid
* expression; it must be expressed as {@code "(a & b) | c"} or
* {@code "a & (b | c)"}.
* <p>As of Spring Framework 5.1.17, two {@code Profiles} instances returned
* by this method are considered equivalent to each other (in terms of
* {@code equals()} and {@code hashCode()} semantics) if they are created
* with identical <em>profile expressions</em>.
* @param profileExpressions the <em>profile expressions</em> to include
* with identical <em>profile strings</em>.
* @param profiles the <em>profile strings</em> to include
* @return a new {@link Profiles} instance
*/
static Profiles of(String... profileExpressions) {
return ProfilesParser.parse(profileExpressions);
static Profiles of(String... profiles) {
return ProfilesParser.parse(profiles);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,7 +43,7 @@ final class ProfilesParser {
static Profiles parse(String... expressions) {
Assert.notEmpty(expressions, "Must specify at least one profile expression");
Assert.notEmpty(expressions, "Must specify at least one profile");
Profiles[] parsed = new Profiles[expressions.length];
for (int i = 0; i < expressions.length; i++) {
parsed[i] = parseExpression(expressions[i]);
@@ -71,8 +71,8 @@ final class ProfilesParser {
}
switch (token) {
case "(":
Profiles contents = parseTokens(expression, tokens, Context.PARENTHESIS);
if (context == Context.NEGATE) {
Profiles contents = parseTokens(expression, tokens, Context.BRACKET);
if (context == Context.INVERT) {
return contents;
}
elements.add(contents);
@@ -86,11 +86,11 @@ final class ProfilesParser {
operator = Operator.OR;
break;
case "!":
elements.add(not(parseTokens(expression, tokens, Context.NEGATE)));
elements.add(not(parseTokens(expression, tokens, Context.INVERT)));
break;
case ")":
Profiles merged = merge(expression, elements, operator);
if (context == Context.PARENTHESIS) {
if (context == Context.BRACKET) {
return merged;
}
elements.clear();
@@ -99,7 +99,7 @@ final class ProfilesParser {
break;
default:
Profiles value = equals(token);
if (context == Context.NEGATE) {
if (context == Context.INVERT) {
return value;
}
elements.add(value);
@@ -137,14 +137,15 @@ final class ProfilesParser {
return activeProfile -> activeProfile.test(profile);
}
private static Predicate<Profiles> isMatch(Predicate<String> activeProfiles) {
return profiles -> profiles.matches(activeProfiles);
private static Predicate<Profiles> isMatch(Predicate<String> activeProfile) {
return profiles -> profiles.matches(activeProfile);
}
private enum Operator { AND, OR }
private enum Operator {AND, OR}
private enum Context { NONE, NEGATE, PARENTHESIS }
private enum Context {NONE, INVERT, BRACKET}
private static class ParsedProfiles implements Profiles {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,15 +33,13 @@ import org.springframework.util.StringUtils;
*
* <p>Supports resolution as {@code java.io.File} if the class path
* resource resides in the file system, but not for resources in a JAR.
* Always supports resolution as {@code java.net.URL}.
* Always supports resolution as URL.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 28.12.2003
* @see ClassLoader#getResourceAsStream(String)
* @see ClassLoader#getResource(String)
* @see Class#getResourceAsStream(String)
* @see Class#getResource(String)
*/
public class ClassPathResource extends AbstractFileResolvingResource {
@@ -126,7 +124,7 @@ public class ClassPathResource extends AbstractFileResolvingResource {
}
/**
* Return the {@link ClassLoader} that this resource will be obtained from.
* Return the ClassLoader that this resource will be obtained from.
*/
@Nullable
public final ClassLoader getClassLoader() {
@@ -136,8 +134,8 @@ public class ClassPathResource extends AbstractFileResolvingResource {
/**
* This implementation checks for the resolution of a resource URL.
* @see ClassLoader#getResource(String)
* @see Class#getResource(String)
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public boolean exists() {
@@ -147,8 +145,8 @@ public class ClassPathResource extends AbstractFileResolvingResource {
/**
* This implementation checks for the resolution of a resource URL upfront,
* then proceeding with {@link AbstractFileResolvingResource}'s length check.
* @see ClassLoader#getResource(String)
* @see Class#getResource(String)
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public boolean isReadable() {
@@ -181,11 +179,9 @@ public class ClassPathResource extends AbstractFileResolvingResource {
}
/**
* This implementation opens an {@link InputStream} for the underlying class
* path resource, if available.
* @see ClassLoader#getResourceAsStream(String)
* @see Class#getResourceAsStream(String)
* @see ClassLoader#getSystemResourceAsStream(String)
* This implementation opens an InputStream for the given class path resource.
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see java.lang.Class#getResourceAsStream(String)
*/
@Override
public InputStream getInputStream() throws IOException {
@@ -208,8 +204,8 @@ public class ClassPathResource extends AbstractFileResolvingResource {
/**
* This implementation returns a URL for the underlying class path resource,
* if available.
* @see ClassLoader#getResource(String)
* @see Class#getResource(String)
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public URL getURL() throws IOException {
@@ -221,9 +217,9 @@ public class ClassPathResource extends AbstractFileResolvingResource {
}
/**
* This implementation creates a {@code ClassPathResource}, applying the given
* path relative to the path used to create this descriptor.
* @see StringUtils#applyRelativePath(String, String)
* This implementation creates a ClassPathResource, applying the given path
* relative to the path of the underlying resource of this descriptor.
* @see org.springframework.util.StringUtils#applyRelativePath(String, String)
*/
@Override
public Resource createRelative(String relativePath) {
@@ -235,7 +231,7 @@ public class ClassPathResource extends AbstractFileResolvingResource {
/**
* This implementation returns the name of the file that this class path
* resource refers to.
* @see StringUtils#getFilename(String)
* @see org.springframework.util.StringUtils#getFilename(String)
*/
@Override
@Nullable
@@ -281,7 +277,8 @@ public class ClassPathResource extends AbstractFileResolvingResource {
}
/**
* This implementation returns the hash code of the underlying class path location.
* This implementation returns the hash code of the underlying
* class path location.
*/
@Override
public int hashCode() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -158,7 +158,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
/**
* This implementation returns whether the underlying file exists.
* @see java.io.File#exists()
* @see java.nio.file.Files#exists(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean exists() {
@@ -170,8 +169,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
* (and corresponds to an actual file with content, not to a directory).
* @see java.io.File#canRead()
* @see java.io.File#isDirectory()
* @see java.nio.file.Files#isReadable(Path)
* @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean isReadable() {
@@ -180,8 +177,8 @@ public class FileSystemResource extends AbstractResource implements WritableReso
}
/**
* This implementation opens an NIO file stream for the underlying file.
* @see java.nio.file.Files#newInputStream(Path, java.nio.file.OpenOption...)
* This implementation opens a NIO file stream for the underlying file.
* @see java.io.FileInputStream
*/
@Override
public InputStream getInputStream() throws IOException {
@@ -198,8 +195,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
* (and corresponds to an actual file with content, not to a directory).
* @see java.io.File#canWrite()
* @see java.io.File#isDirectory()
* @see java.nio.file.Files#isWritable(Path)
* @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean isWritable() {
@@ -209,7 +204,7 @@ public class FileSystemResource extends AbstractResource implements WritableReso
/**
* This implementation opens a FileOutputStream for the underlying file.
* @see java.nio.file.Files#newOutputStream(Path, java.nio.file.OpenOption...)
* @see java.io.FileOutputStream
*/
@Override
public OutputStream getOutputStream() throws IOException {
@@ -219,7 +214,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
/**
* This implementation returns a URL for the underlying file.
* @see java.io.File#toURI()
* @see java.nio.file.Path#toUri()
*/
@Override
public URL getURL() throws IOException {
@@ -229,7 +223,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
/**
* This implementation returns a URI for the underlying file.
* @see java.io.File#toURI()
* @see java.nio.file.Path#toUri()
*/
@Override
public URI getURI() throws IOException {
@@ -331,7 +324,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
/**
* This implementation returns the name of the file.
* @see java.io.File#getName()
* @see java.nio.file.Path#getFileName()
*/
@Override
public String getFilename() {
@@ -342,7 +334,6 @@ public class FileSystemResource extends AbstractResource implements WritableReso
* This implementation returns a description that includes the absolute
* path of the file.
* @see java.io.File#getAbsolutePath()
* @see java.nio.file.Path#toAbsolutePath()
*/
@Override
public String getDescription() {
@@ -351,7 +342,7 @@ public class FileSystemResource extends AbstractResource implements WritableReso
/**
* This implementation compares the underlying file paths.
* This implementation compares the underlying File references.
*/
@Override
public boolean equals(@Nullable Object other) {
@@ -360,7 +351,7 @@ public class FileSystemResource extends AbstractResource implements WritableReso
}
/**
* This implementation returns the hash code of the underlying file path.
* This implementation returns the hash code of the underlying File reference.
*/
@Override
public int hashCode() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,7 +61,7 @@ public class PathResource extends AbstractResource implements WritableResource {
/**
* Create a new {@code PathResource} from a {@link Path} handle.
* Create a new PathResource from a Path handle.
* <p>Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built <i>underneath</i>
* the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" &rarr; "C:/dir1/dir2"!
@@ -73,7 +73,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* Create a new {@code PathResource} from a path string.
* Create a new PathResource from a Path handle.
* <p>Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built <i>underneath</i>
* the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" &rarr; "C:/dir1/dir2"!
@@ -86,7 +86,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* Create a new {@code PathResource} from a {@link URI}.
* Create a new PathResource from a Path handle.
* <p>Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built <i>underneath</i>
* the given root: e.g. Paths.get("C:/dir1/"), relative path "dir2" &rarr; "C:/dir1/dir2"!
@@ -127,7 +127,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation opens an {@link InputStream} for the underlying file.
* This implementation opens a InputStream for the underlying file.
* @see java.nio.file.spi.FileSystemProvider#newInputStream(Path, OpenOption...)
*/
@Override
@@ -153,7 +153,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation opens an {@link OutputStream} for the underlying file.
* This implementation opens a OutputStream for the underlying file.
* @see java.nio.file.spi.FileSystemProvider#newOutputStream(Path, OpenOption...)
*/
@Override
@@ -165,7 +165,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation returns a {@link URL} for the underlying file.
* This implementation returns a URL for the underlying file.
* @see java.nio.file.Path#toUri()
* @see java.net.URI#toURL()
*/
@@ -175,7 +175,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation returns a {@link URI} for the underlying file.
* This implementation returns a URI for the underlying file.
* @see java.nio.file.Path#toUri()
*/
@Override
@@ -192,7 +192,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation returns the underlying {@link File} reference.
* This implementation returns the underlying File reference.
*/
@Override
public File getFile() throws IOException {
@@ -207,7 +207,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation opens a {@link ReadableByteChannel} for the underlying file.
* This implementation opens a Channel for the underlying file.
* @see Files#newByteChannel(Path, OpenOption...)
*/
@Override
@@ -221,7 +221,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation opens a {@link WritableByteChannel} for the underlying file.
* This implementation opens a Channel for the underlying file.
* @see Files#newByteChannel(Path, OpenOption...)
*/
@Override
@@ -238,7 +238,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation returns the underlying file's timestamp.
* This implementation returns the underlying File's timestamp.
* @see java.nio.file.Files#getLastModifiedTime(Path, java.nio.file.LinkOption...)
*/
@Override
@@ -249,7 +249,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation creates a {@link PathResource}, applying the given path
* This implementation creates a PathResource, applying the given path
* relative to the path of the underlying file of this resource descriptor.
* @see java.nio.file.Path#resolve(String)
*/
@@ -274,7 +274,7 @@ public class PathResource extends AbstractResource implements WritableResource {
/**
* This implementation compares the underlying {@link Path} references.
* This implementation compares the underlying Path references.
*/
@Override
public boolean equals(@Nullable Object other) {
@@ -283,7 +283,7 @@ public class PathResource extends AbstractResource implements WritableResource {
}
/**
* This implementation returns the hash code of the underlying {@link Path} reference.
* This implementation returns the hash code of the underlying Path reference.
*/
@Override
public int hashCode() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import org.apache.commons.logging.Log;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Utility methods for formatting and logging messages.
@@ -79,7 +78,7 @@ public abstract class LogFormatUtils {
result = ObjectUtils.nullSafeToString(ex);
}
if (maxLength != -1) {
result = StringUtils.truncate(result, maxLength);
result = (result.length() > maxLength ? result.substring(0, maxLength) + " (truncated)..." : result);
}
if (replaceNewlinesAndControlCharacters) {
result = NEWLINE_PATTERN.matcher(result).replaceAll("<EOL>");
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,7 +50,6 @@ public class DefaultDeserializer implements Deserializer<Object> {
/**
* Create a {@code DefaultDeserializer} for using an {@link ObjectInputStream}
* with the given {@code ClassLoader}.
* @param classLoader the ClassLoader to use
* @since 4.2.1
* @see ConfigurableObjectInputStream#ConfigurableObjectInputStream(InputStream, ClassLoader)
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@ import java.io.ByteArrayInputStream;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.DefaultDeserializer;
import org.springframework.core.serializer.Deserializer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@@ -51,11 +50,10 @@ public class DeserializingConverter implements Converter<byte[], Object> {
/**
* Create a {@code DeserializingConverter} for using an {@link java.io.ObjectInputStream}
* with the given {@code ClassLoader}.
* @param classLoader the ClassLoader to use
* @since 4.2.1
* @see DefaultDeserializer#DefaultDeserializer(ClassLoader)
*/
public DeserializingConverter(@Nullable ClassLoader classLoader) {
public DeserializingConverter(ClassLoader classLoader) {
this.deserializer = new DefaultDeserializer(classLoader);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,10 +68,10 @@ public abstract class FileSystemUtils {
}
/**
* Delete the supplied {@link Path} &mdash; for directories,
* Delete the supplied {@link File} &mdash; for directories,
* recursively delete any nested directories or files as well.
* @param root the root {@code Path} to delete
* @return {@code true} if the {@code Path} existed and was deleted,
* @param root the root {@code File} to delete
* @return {@code true} if the {@code File} existed and was deleted,
* or {@code false} if it did not exist
* @throws IOException in the case of I/O errors
* @since 5.0
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,26 +16,12 @@
package org.springframework.util;
import java.io.File;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.time.ZoneId;
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.lang.Nullable;
@@ -69,9 +55,6 @@ public abstract class ObjectUtils {
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
private static final String NON_EMPTY_ARRAY = ARRAY_START + "..." + ARRAY_END;
private static final String EMPTY_COLLECTION = "[]";
private static final String NON_EMPTY_COLLECTION = "[...]";
/**
@@ -670,7 +653,6 @@ public abstract class ObjectUtils {
* Returns a {@code "null"} String if {@code obj} is {@code null}.
* @param obj the object to build a String representation for
* @return a String representation of {@code obj}
* @see #nullSafeConciseToString(Object)
*/
public static String nullSafeToString(@Nullable Object obj) {
if (obj == null) {
@@ -926,117 +908,4 @@ public abstract class ObjectUtils {
return stringJoiner.toString();
}
/**
* Generate a null-safe, concise string representation of the supplied object
* as described below.
* <p>Favor this method over {@link #nullSafeToString(Object)} when you need
* the length of the generated string to be limited.
* <p>Returns:
* <ul>
* <li>{@code "null"} if {@code obj} is {@code null}</li>
* <li>{@code"Optional.empty"} if {@code obj} is an empty {@link Optional}</li>
* <li>{@code"Optional[<concise-string>]"} if {@code obj} is a non-empty {@code Optional},
* where {@code <concise-string>} is the result of invoking {@link #nullSafeConciseToString}
* on the object contained in the {@code Optional}</li>
* <li>{@code "{}"} if {@code obj} is an empty array or {@link Map}</li>
* <li>{@code "{...}"} if {@code obj} is a non-empty array or {@link Map}</li>
* <li>{@code "[]"} if {@code obj} is an empty {@link Collection}</li>
* <li>{@code "[...]"} if {@code obj} is a non-empty {@link Collection}</li>
* <li>{@linkplain Class#getName() Class name} if {@code obj} is a {@link Class}</li>
* <li>{@linkplain Charset#name() Charset name} if {@code obj} is a {@link Charset}</li>
* <li>{@linkplain TimeZone#getID() TimeZone ID} if {@code obj} is a {@link TimeZone}</li>
* <li>{@linkplain ZoneId#getId() Zone ID} if {@code obj} is a {@link ZoneId}</li>
* <li>Potentially {@linkplain StringUtils#truncate(CharSequence) truncated string}
* if {@code obj} is a {@link String} or {@link CharSequence}</li>
* <li>Potentially {@linkplain StringUtils#truncate(CharSequence) truncated string}
* if {@code obj} is a <em>simple value type</em> whose {@code toString()} method
* returns a non-null value</li>
* <li>Otherwise, a string representation of the object's type name concatenated
* with {@code "@"} and a hex string form of the object's identity hash code</li>
* </ul>
* <p>In the context of this method, a <em>simple value type</em> is any of the following:
* primitive wrapper (excluding {@link Void}), {@link Enum}, {@link Number},
* {@link Date}, {@link Temporal}, {@link File}, {@link Path}, {@link URI},
* {@link URL}, {@link InetAddress}, {@link Currency}, {@link Locale},
* {@link UUID}, {@link Pattern}.
* @param obj the object to build a string representation for
* @return a concise string representation of the supplied object
* @since 5.3.27
* @see #nullSafeToString(Object)
* @see StringUtils#truncate(CharSequence)
*/
public static String nullSafeConciseToString(@Nullable Object obj) {
if (obj == null) {
return "null";
}
if (obj instanceof Optional<?>) {
Optional<?> optional = (Optional<?>) obj;
return (!optional.isPresent() ? "Optional.empty" :
String.format("Optional[%s]", nullSafeConciseToString(optional.get())));
}
if (obj.getClass().isArray()) {
return (Array.getLength(obj) == 0 ? EMPTY_ARRAY : NON_EMPTY_ARRAY);
}
if (obj instanceof Collection<?>) {
return (((Collection<?>) obj).isEmpty() ? EMPTY_COLLECTION : NON_EMPTY_COLLECTION);
}
if (obj instanceof Map<?, ?>) {
// EMPTY_ARRAY and NON_EMPTY_ARRAY are also used for maps.
return (((Map<?, ?>) obj).isEmpty() ? EMPTY_ARRAY : NON_EMPTY_ARRAY);
}
if (obj instanceof Class<?>) {
return ((Class<?>) obj).getName();
}
if (obj instanceof Charset) {
return ((Charset) obj).name();
}
if (obj instanceof TimeZone) {
return ((TimeZone) obj).getID();
}
if (obj instanceof ZoneId) {
return ((ZoneId) obj).getId();
}
if (obj instanceof CharSequence) {
return StringUtils.truncate((CharSequence) obj);
}
Class<?> type = obj.getClass();
if (isSimpleValueType(type)) {
String str = obj.toString();
if (str != null) {
return StringUtils.truncate(str);
}
}
return type.getTypeName() + "@" + getIdentityHexString(obj);
}
/**
* Derived from {@link org.springframework.beans.BeanUtils#isSimpleValueType}.
* <p>As of 5.3.28, considering {@link UUID} in addition to the bean-level check.
* <p>As of 5.3.29, additionally considering {@link File}, {@link Path},
* {@link InetAddress}, {@link Charset}, {@link Currency}, {@link TimeZone},
* {@link ZoneId}, {@link Pattern}.
*/
private static boolean isSimpleValueType(Class<?> type) {
return (Void.class != type && void.class != type &&
(ClassUtils.isPrimitiveOrWrapper(type) ||
Enum.class.isAssignableFrom(type) ||
CharSequence.class.isAssignableFrom(type) ||
Number.class.isAssignableFrom(type) ||
Date.class.isAssignableFrom(type) ||
Temporal.class.isAssignableFrom(type) ||
ZoneId.class.isAssignableFrom(type) ||
TimeZone.class.isAssignableFrom(type) ||
File.class.isAssignableFrom(type) ||
Path.class.isAssignableFrom(type) ||
Charset.class.isAssignableFrom(type) ||
Currency.class.isAssignableFrom(type) ||
InetAddress.class.isAssignableFrom(type) ||
URI.class == type ||
URL.class == type ||
UUID.class == type ||
Locale.class == type ||
Pattern.class == type ||
Class.class == type));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -509,8 +509,16 @@ public abstract class ReflectionUtils {
* @see java.lang.Object#equals(Object)
*/
public static boolean isEqualsMethod(@Nullable Method method) {
return (method != null && method.getParameterCount() == 1 && method.getName().equals("equals") &&
method.getParameterTypes()[0] == Object.class);
if (method == null) {
return false;
}
if (method.getParameterCount() != 1) {
return false;
}
if (!method.getName().equals("equals")) {
return false;
}
return method.getParameterTypes()[0] == Object.class;
}
/**
@@ -518,7 +526,7 @@ public abstract class ReflectionUtils {
* @see java.lang.Object#hashCode()
*/
public static boolean isHashCodeMethod(@Nullable Method method) {
return (method != null && method.getParameterCount() == 0 && method.getName().equals("hashCode"));
return method != null && method.getParameterCount() == 0 && method.getName().equals("hashCode");
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -75,10 +75,6 @@ public abstract class StringUtils {
private static final char EXTENSION_SEPARATOR = '.';
private static final int DEFAULT_TRUNCATION_THRESHOLD = 100;
private static final String TRUNCATION_SUFFIX = " (truncated)...";
//---------------------------------------------------------------------
// General convenience methods for working with Strings
@@ -1392,40 +1388,4 @@ public abstract class StringUtils {
return arrayToDelimitedString(arr, ",");
}
/**
* Truncate the supplied {@link CharSequence}.
* <p>Delegates to {@link #truncate(CharSequence, int)}, supplying {@code 100}
* as the threshold.
* @param charSequence the {@code CharSequence} to truncate
* @return a truncated string, or a string representation of the original
* {@code CharSequence} if its length does not exceed the threshold
* @since 5.3.27
*/
public static String truncate(CharSequence charSequence) {
return truncate(charSequence, DEFAULT_TRUNCATION_THRESHOLD);
}
/**
* Truncate the supplied {@link CharSequence}.
* <p>If the length of the {@code CharSequence} is greater than the threshold,
* this method returns a {@linkplain CharSequence#subSequence(int, int)
* subsequence} of the {@code CharSequence} (up to the threshold) appended
* with the suffix {@code " (truncated)..."}. Otherwise, this method returns
* {@code charSequence.toString()}.
* @param charSequence the {@code CharSequence} to truncate
* @param threshold the maximum length after which to truncate; must be a
* positive number
* @return a truncated string, or a string representation of the original
* {@code CharSequence} if its length does not exceed the threshold
* @since 5.3.27
*/
public static String truncate(CharSequence charSequence, int threshold) {
Assert.isTrue(threshold > 0,
() -> "Truncation threshold must be a positive number: " + threshold);
if (charSequence.length() > threshold) {
return charSequence.subSequence(0, threshold) + TRUNCATION_SUFFIX;
}
return charSequence.toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -209,23 +209,21 @@ class CollectionFactoryTests {
@Test
void createsCollectionsCorrectly() {
// interfaces
testCollection(List.class, ArrayList.class);
testCollection(Set.class, LinkedHashSet.class);
testCollection(Collection.class, LinkedHashSet.class);
testCollection(SortedSet.class, TreeSet.class);
testCollection(NavigableSet.class, TreeSet.class);
assertThat(createCollection(List.class, 0)).isInstanceOf(ArrayList.class);
assertThat(createCollection(Set.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(Collection.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(SortedSet.class, 0)).isInstanceOf(TreeSet.class);
assertThat(createCollection(NavigableSet.class, 0)).isInstanceOf(TreeSet.class);
assertThat(createCollection(List.class, String.class, 0)).isInstanceOf(ArrayList.class);
assertThat(createCollection(Set.class, String.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(Collection.class, String.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(SortedSet.class, String.class, 0)).isInstanceOf(TreeSet.class);
assertThat(createCollection(NavigableSet.class, String.class, 0)).isInstanceOf(TreeSet.class);
// concrete types
testCollection(ArrayList.class, ArrayList.class);
testCollection(HashSet.class, HashSet.class);
testCollection(LinkedHashSet.class, LinkedHashSet.class);
testCollection(TreeSet.class, TreeSet.class);
}
private void testCollection(Class<?> collectionType, Class<?> resultType) {
assertThat(CollectionFactory.isApproximableCollectionType(collectionType)).isTrue();
assertThat(createCollection(collectionType, 0)).isExactlyInstanceOf(resultType);
assertThat(createCollection(collectionType, String.class, 0)).isExactlyInstanceOf(resultType);
assertThat(createCollection(HashSet.class, 0)).isInstanceOf(HashSet.class);
assertThat(createCollection(HashSet.class, String.class, 0)).isInstanceOf(HashSet.class);
}
@Test
@@ -260,22 +258,20 @@ class CollectionFactoryTests {
@Test
void createsMapsCorrectly() {
// interfaces
testMap(Map.class, LinkedHashMap.class);
testMap(SortedMap.class, TreeMap.class);
testMap(NavigableMap.class, TreeMap.class);
testMap(MultiValueMap.class, LinkedMultiValueMap.class);
assertThat(createMap(Map.class, 0)).isInstanceOf(LinkedHashMap.class);
assertThat(createMap(SortedMap.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(NavigableMap.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(MultiValueMap.class, 0)).isInstanceOf(LinkedMultiValueMap.class);
assertThat(createMap(Map.class, String.class, 0)).isInstanceOf(LinkedHashMap.class);
assertThat(createMap(SortedMap.class, String.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(NavigableMap.class, String.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(MultiValueMap.class, String.class, 0)).isInstanceOf(LinkedMultiValueMap.class);
// concrete types
testMap(HashMap.class, HashMap.class);
testMap(LinkedHashMap.class, LinkedHashMap.class);
testMap(TreeMap.class, TreeMap.class);
testMap(LinkedMultiValueMap.class, LinkedMultiValueMap.class);
}
assertThat(createMap(HashMap.class, 0)).isInstanceOf(HashMap.class);
private void testMap(Class<?> mapType, Class<?> resultType) {
assertThat(CollectionFactory.isApproximableMapType(mapType)).isTrue();
assertThat(createMap(mapType, 0)).isExactlyInstanceOf(resultType);
assertThat(createMap(mapType, String.class, 0)).isExactlyInstanceOf(resultType);
assertThat(createMap(HashMap.class, String.class, 0)).isInstanceOf(HashMap.class);
}
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -342,31 +342,20 @@ class DefaultConversionServiceTests {
@Test
void convertArrayToCollectionInterface() {
@SuppressWarnings("unchecked")
Collection<String> result = conversionService.convert(new String[] {"1", "2", "3"}, Collection.class);
assertThat(result).isExactlyInstanceOf(LinkedHashSet.class).containsExactly("1", "2", "3");
}
@Test
void convertArrayToSetInterface() {
@SuppressWarnings("unchecked")
Collection<String> result = conversionService.convert(new String[] {"1", "2", "3"}, Set.class);
assertThat(result).isExactlyInstanceOf(LinkedHashSet.class).containsExactly("1", "2", "3");
}
@Test
void convertArrayToListInterface() {
@SuppressWarnings("unchecked")
List<String> result = conversionService.convert(new String[] {"1", "2", "3"}, List.class);
assertThat(result).isExactlyInstanceOf(ArrayList.class).containsExactly("1", "2", "3");
List<?> result = conversionService.convert(new String[] {"1", "2", "3"}, List.class);
assertThat(result.get(0)).isEqualTo("1");
assertThat(result.get(1)).isEqualTo("2");
assertThat(result.get(2)).isEqualTo("3");
}
@Test
void convertArrayToCollectionGenericTypeConversion() throws Exception {
@SuppressWarnings("unchecked")
List<Integer> result = (List<Integer>) conversionService.convert(new String[] {"1", "2", "3"},
TypeDescriptor.valueOf(String[].class), new TypeDescriptor(getClass().getDeclaredField("genericList")));
assertThat(result).isExactlyInstanceOf(ArrayList.class).containsExactly(1, 2, 3);
List<Integer> result = (List<Integer>) conversionService.convert(new String[] {"1", "2", "3"}, TypeDescriptor
.valueOf(String[].class), new TypeDescriptor(getClass().getDeclaredField("genericList")));
assertThat((int) result.get(0)).isEqualTo((int) Integer.valueOf(1));
assertThat((int) result.get(1)).isEqualTo((int) Integer.valueOf(2));
assertThat((int) result.get(2)).isEqualTo((int) Integer.valueOf(3));
}
@Test
@@ -394,9 +383,10 @@ class DefaultConversionServiceTests {
@Test
void convertArrayToCollectionImpl() {
@SuppressWarnings("unchecked")
ArrayList<String> result = conversionService.convert(new String[] {"1", "2", "3"}, ArrayList.class);
assertThat(result).isExactlyInstanceOf(ArrayList.class).containsExactly("1", "2", "3");
ArrayList<?> result = conversionService.convert(new String[] {"1", "2", "3"}, ArrayList.class);
assertThat(result.get(0)).isEqualTo("1");
assertThat(result.get(1)).isEqualTo("2");
assertThat(result.get(2)).isEqualTo("3");
}
@Test
@@ -426,25 +416,34 @@ class DefaultConversionServiceTests {
@Test
void convertStringToArray() {
String[] result = conversionService.convert("1,2,3", String[].class);
assertThat(result).containsExactly("1", "2", "3");
assertThat(result.length).isEqualTo(3);
assertThat(result[0]).isEqualTo("1");
assertThat(result[1]).isEqualTo("2");
assertThat(result[2]).isEqualTo("3");
}
@Test
void convertStringToArrayWithElementConversion() {
Integer[] result = conversionService.convert("1,2,3", Integer[].class);
assertThat(result).containsExactly(1, 2, 3);
assertThat(result.length).isEqualTo(3);
assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1));
assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2));
assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3));
}
@Test
void convertStringToPrimitiveArrayWithElementConversion() {
int[] result = conversionService.convert("1,2,3", int[].class);
assertThat(result).containsExactly(1, 2, 3);
assertThat(result.length).isEqualTo(3);
assertThat(result[0]).isEqualTo(1);
assertThat(result[1]).isEqualTo(2);
assertThat(result[2]).isEqualTo(3);
}
@Test
void convertEmptyStringToArray() {
String[] result = conversionService.convert("", String[].class);
assertThat(result).isEmpty();
assertThat(result.length).isEqualTo(0);
}
@Test
@@ -458,7 +457,7 @@ class DefaultConversionServiceTests {
void convertArrayToObjectWithElementConversion() {
String[] array = new String[] {"3"};
Integer result = conversionService.convert(array, Integer.class);
assertThat(result).isEqualTo(3);
assertThat((int) result).isEqualTo((int) Integer.valueOf(3));
}
@Test
@@ -471,27 +470,39 @@ class DefaultConversionServiceTests {
@Test
void convertObjectToArray() {
Object[] result = conversionService.convert(3L, Object[].class);
assertThat(result).containsExactly(3L);
assertThat(result.length).isEqualTo(1);
assertThat(result[0]).isEqualTo(3L);
}
@Test
void convertObjectToArrayWithElementConversion() {
Integer[] result = conversionService.convert(3L, Integer[].class);
assertThat(result).containsExactly(3);
assertThat(result.length).isEqualTo(1);
assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(3));
}
@Test
void convertCollectionToArray() {
List<String> list = Arrays.asList("1", "2", "3");
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
String[] result = conversionService.convert(list, String[].class);
assertThat(result).containsExactly("1", "2", "3");
assertThat(result[0]).isEqualTo("1");
assertThat(result[1]).isEqualTo("2");
assertThat(result[2]).isEqualTo("3");
}
@Test
void convertCollectionToArrayWithElementConversion() {
List<String> list = Arrays.asList("1", "2", "3");
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
Integer[] result = conversionService.convert(list, Integer[].class);
assertThat(result).containsExactly(1, 2, 3);
assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1));
assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2));
assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3));
}
@Test
@@ -511,30 +522,34 @@ class DefaultConversionServiceTests {
@Test
void convertStringToCollection() {
@SuppressWarnings("unchecked")
List<String> result = conversionService.convert("1,2,3", List.class);
assertThat(result).containsExactly("1", "2", "3");
List<?> result = conversionService.convert("1,2,3", List.class);
assertThat(result.size()).isEqualTo(3);
assertThat(result.get(0)).isEqualTo("1");
assertThat(result.get(1)).isEqualTo("2");
assertThat(result.get(2)).isEqualTo("3");
}
@Test
void convertStringToCollectionWithElementConversion() throws Exception {
@SuppressWarnings("unchecked")
List<Integer> result = (List<Integer>) conversionService.convert("1,2,3", TypeDescriptor.valueOf(String.class),
List<?> result = (List<?>) conversionService.convert("1,2,3", TypeDescriptor.valueOf(String.class),
new TypeDescriptor(getClass().getField("genericList")));
assertThat(result).containsExactly(1, 2, 3);
assertThat(result.size()).isEqualTo(3);
assertThat(result.get(0)).isEqualTo(1);
assertThat(result.get(1)).isEqualTo(2);
assertThat(result.get(2)).isEqualTo(3);
}
@Test
void convertEmptyStringToCollection() {
Collection<?> result = conversionService.convert("", Collection.class);
assertThat(result).isEmpty();
assertThat(result.size()).isEqualTo(0);
}
@Test
void convertCollectionToObject() {
List<Long> list = Collections.singletonList(3L);
Long result = conversionService.convert(list, Long.class);
assertThat(result).isEqualTo(3);
assertThat(result).isEqualTo(Long.valueOf(3));
}
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,30 +40,30 @@ class ProfilesTests {
@Test
void ofWhenNullThrowsException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> Profiles.of((String[]) null))
.withMessage("Must specify at least one profile expression");
assertThatIllegalArgumentException().isThrownBy(() ->
Profiles.of((String[]) null))
.withMessageContaining("Must specify at least one profile");
}
@Test
void ofWhenEmptyThrowsException() {
assertThatIllegalArgumentException()
.isThrownBy(Profiles::of)
.withMessage("Must specify at least one profile expression");
.withMessageContaining("Must specify at least one profile");
}
@Test
void ofNullElement() {
assertThatIllegalArgumentException()
.isThrownBy(() -> Profiles.of((String) null))
.withMessage("Invalid profile expression [null]: must contain text");
assertThatIllegalArgumentException().isThrownBy(() ->
Profiles.of((String) null))
.withMessageContaining("must contain text");
}
@Test
void ofEmptyElement() {
assertThatIllegalArgumentException()
.isThrownBy(() -> Profiles.of(" "))
.withMessage("Invalid profile expression [ ]: must contain text");
assertThatIllegalArgumentException().isThrownBy(() ->
Profiles.of(" "))
.withMessageContaining("must contain text");
}
@Test
@@ -356,7 +356,7 @@ class ProfilesTests {
private static void assertMalformed(Supplier<Profiles> supplier) {
assertThatIllegalArgumentException()
.isThrownBy(supplier::get)
.withMessageStartingWith("Malformed profile expression");
.withMessageContaining("Malformed");
}
private static Predicate<String> activeProfiles(String... profiles) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,9 +18,9 @@ package org.springframework.core.env;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.Arrays;
import java.util.Map;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.core.SpringProperties;
@@ -40,7 +40,8 @@ import static org.springframework.core.env.AbstractEnvironment.RESERVED_DEFAULT_
* @author Juergen Hoeller
* @author Sam Brannen
*/
class StandardEnvironmentTests {
@SuppressWarnings("deprecation")
public class StandardEnvironmentTests {
private static final String ALLOWED_PROPERTY_NAME = "theanswer";
private static final String ALLOWED_PROPERTY_VALUE = "42";
@@ -80,8 +81,8 @@ class StandardEnvironmentTests {
assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal");
assertThat(child.getActiveProfiles()).containsExactly("c1", "c2");
assertThat(parent.getActiveProfiles()).containsExactly("p1", "p2");
assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2"});
assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"});
child.merge(parent);
@@ -93,8 +94,8 @@ class StandardEnvironmentTests {
assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal");
assertThat(child.getActiveProfiles()).containsExactly("c1", "c2", "p1", "p2");
assertThat(parent.getActiveProfiles()).containsExactly("p1", "p2");
assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2","p1","p2"});
assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"});
}
@Test
@@ -120,14 +121,16 @@ class StandardEnvironmentTests {
@Test
void defaultProfilesContainsDefaultProfileByDefault() {
assertThat(environment.getDefaultProfiles()).containsExactly("default");
assertThat(environment.getDefaultProfiles().length).isEqualTo(1);
assertThat(environment.getDefaultProfiles()[0]).isEqualTo("default");
}
@Test
void setActiveProfiles() {
environment.setActiveProfiles("local", "embedded");
String[] activeProfiles = environment.getActiveProfiles();
assertThat(activeProfiles).containsExactly("local", "embedded");
assertThat(activeProfiles).contains("local", "embedded");
assertThat(activeProfiles.length).isEqualTo(2);
}
@Test
@@ -174,12 +177,15 @@ class StandardEnvironmentTests {
void addActiveProfile() {
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
environment.setActiveProfiles("local", "embedded");
assertThat(environment.getActiveProfiles()).containsExactly("local", "embedded");
assertThat(environment.getActiveProfiles()).contains("local", "embedded");
assertThat(environment.getActiveProfiles().length).isEqualTo(2);
environment.addActiveProfile("p1");
assertThat(environment.getActiveProfiles()).containsExactly("local", "embedded", "p1");
assertThat(environment.getActiveProfiles()).contains("p1");
assertThat(environment.getActiveProfiles().length).isEqualTo(3);
environment.addActiveProfile("p2");
environment.addActiveProfile("p3");
assertThat(environment.getActiveProfiles()).containsExactly("local", "embedded", "p1", "p2", "p3");
assertThat(environment.getActiveProfiles()).contains("p2", "p3");
assertThat(environment.getActiveProfiles().length).isEqualTo(5);
}
@Test
@@ -189,41 +195,65 @@ class StandardEnvironmentTests {
env.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isEqualTo("p1");
env.addActiveProfile("p2");
assertThat(env.getActiveProfiles()).containsExactly("p1", "p2");
assertThat(env.getActiveProfiles()).contains("p1", "p2");
}
@Test
void reservedDefaultProfile() {
assertThat(environment.getDefaultProfiles()).containsExactly(RESERVED_DEFAULT_PROFILE_NAME);
try {
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "d0");
assertThat(environment.getDefaultProfiles()).containsExactly("d0");
environment.setDefaultProfiles("d1", "d2");
assertThat(environment.getDefaultProfiles()).containsExactly("d1","d2");
}
finally {
System.clearProperty(DEFAULT_PROFILES_PROPERTY_NAME);
}
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{RESERVED_DEFAULT_PROFILE_NAME});
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "d0");
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d0"});
environment.setDefaultProfiles("d1", "d2");
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d1","d2"});
System.clearProperty(DEFAULT_PROFILES_PROPERTY_NAME);
}
@Test
void defaultProfileWithCircularPlaceholder() {
try {
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "${spring.profiles.default}");
assertThatIllegalArgumentException()
.isThrownBy(environment::getDefaultProfiles)
.withMessage("Circular placeholder reference 'spring.profiles.default' in property definitions");
assertThatIllegalArgumentException().isThrownBy(environment::getDefaultProfiles);
}
finally {
System.clearProperty(DEFAULT_PROFILES_PROPERTY_NAME);
}
}
@Test
void getActiveProfiles_systemPropertiesEmpty() {
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "");
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getActiveProfiles_fromSystemProperties() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo");
assertThat(Arrays.asList(environment.getActiveProfiles())).contains("foo");
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getActiveProfiles_fromSystemProperties_withMultipleProfiles() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar");
assertThat(environment.getActiveProfiles()).contains("foo", "bar");
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getActiveProfiles_fromSystemProperties_withMultipleProfiles_withWhitespace() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace
assertThat(environment.getActiveProfiles()).contains("bar", "baz");
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
void getDefaultProfiles() {
assertThat(environment.getDefaultProfiles()).containsExactly(RESERVED_DEFAULT_PROFILE_NAME);
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[] {RESERVED_DEFAULT_PROFILE_NAME});
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(DEFAULT_PROFILES_PROPERTY_NAME, "pd1"));
assertThat(environment.getDefaultProfiles()).containsExactly("pd1");
assertThat(environment.getDefaultProfiles().length).isEqualTo(1);
assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1");
}
@Test
@@ -231,9 +261,82 @@ class StandardEnvironmentTests {
environment.setDefaultProfiles();
assertThat(environment.getDefaultProfiles().length).isEqualTo(0);
environment.setDefaultProfiles("pd1");
assertThat(environment.getDefaultProfiles()).containsExactly("pd1");
assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1");
environment.setDefaultProfiles("pd2", "pd3");
assertThat(environment.getDefaultProfiles()).containsExactly("pd2", "pd3");
assertThat(environment.getDefaultProfiles()).doesNotContain("pd1");
assertThat(environment.getDefaultProfiles()).contains("pd2", "pd3");
}
@Test
void acceptsProfiles_withEmptyArgumentList() {
assertThatIllegalArgumentException().isThrownBy(
environment::acceptsProfiles);
}
@Test
void acceptsProfiles_withNullArgumentList() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles((String[]) null));
}
@Test
void acceptsProfiles_withNullArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles((String) null));
}
@Test
void acceptsProfiles_withEmptyArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles(""));
}
@Test
void acceptsProfiles_activeProfileSetProgrammatically() {
assertThat(environment.acceptsProfiles("p1", "p2")).isFalse();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p2");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p1", "p2");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
}
@Test
void acceptsProfiles_activeProfileSetViaProperty() {
assertThat(environment.acceptsProfiles("p1")).isFalse();
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
void acceptsProfiles_defaultProfile() {
assertThat(environment.acceptsProfiles("pd")).isFalse();
environment.setDefaultProfiles("pd");
assertThat(environment.acceptsProfiles("pd")).isTrue();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("pd")).isFalse();
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
void acceptsProfiles_withNotOperator() {
assertThat(environment.acceptsProfiles("p1")).isFalse();
assertThat(environment.acceptsProfiles("!p1")).isTrue();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles("p1")).isTrue();
assertThat(environment.acceptsProfiles("!p1")).isFalse();
}
@Test
void acceptsProfiles_withInvalidNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles("p1", "!"));
}
@Test
void acceptsProfiles_withProfileExpression() {
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p2");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isTrue();
}
@Test
@@ -243,99 +346,88 @@ class StandardEnvironmentTests {
protected void validateProfile(String profile) {
super.validateProfile(profile);
if (profile.contains("-")) {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must not contain dash character");
throw new IllegalArgumentException(
"Invalid profile [" + profile + "]: must not contain dash character");
}
}
};
env.addActiveProfile("validProfile"); // succeeds
assertThatIllegalArgumentException()
.isThrownBy(() -> env.addActiveProfile("invalid-profile"))
assertThatIllegalArgumentException().isThrownBy(() ->
env.addActiveProfile("invalid-profile"))
.withMessage("Invalid profile [invalid-profile]: must not contain dash character");
}
@Test
void suppressGetenvAccessThroughSystemProperty() {
try {
System.setProperty("spring.getenv.ignore", "true");
assertThat(environment.getSystemEnvironment()).isEmpty();
}
finally {
System.clearProperty("spring.getenv.ignore");
}
System.setProperty("spring.getenv.ignore", "true");
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
System.clearProperty("spring.getenv.ignore");
}
@Test
void suppressGetenvAccessThroughSpringProperty() {
try {
SpringProperties.setProperty("spring.getenv.ignore", "true");
assertThat(environment.getSystemEnvironment()).isEmpty();
}
finally {
SpringProperties.setProperty("spring.getenv.ignore", null);
}
SpringProperties.setProperty("spring.getenv.ignore", "true");
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
SpringProperties.setProperty("spring.getenv.ignore", null);
}
@Test
void suppressGetenvAccessThroughSpringFlag() {
try {
SpringProperties.setFlag("spring.getenv.ignore");
assertThat(environment.getSystemEnvironment()).isEmpty();
}
finally {
SpringProperties.setProperty("spring.getenv.ignore", null);
}
SpringProperties.setFlag("spring.getenv.ignore");
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
SpringProperties.setProperty("spring.getenv.ignore", null);
}
@Test
void getSystemProperties_withAndWithoutSecurityManager() {
SecurityManager originalSecurityManager = System.getSecurityManager();
try {
System.setProperty(ALLOWED_PROPERTY_NAME, ALLOWED_PROPERTY_VALUE);
System.setProperty(DISALLOWED_PROPERTY_NAME, DISALLOWED_PROPERTY_VALUE);
System.getProperties().put(STRING_PROPERTY_NAME, NON_STRING_PROPERTY_VALUE);
System.getProperties().put(NON_STRING_PROPERTY_NAME, STRING_PROPERTY_VALUE);
System.setProperty(ALLOWED_PROPERTY_NAME, ALLOWED_PROPERTY_VALUE);
System.setProperty(DISALLOWED_PROPERTY_NAME, DISALLOWED_PROPERTY_VALUE);
System.getProperties().put(STRING_PROPERTY_NAME, NON_STRING_PROPERTY_VALUE);
System.getProperties().put(NON_STRING_PROPERTY_NAME, STRING_PROPERTY_VALUE);
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties).isNotNull();
assertThat(System.getProperties()).isSameAs(systemProperties);
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE);
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties).isNotNull();
assertThat(System.getProperties()).isSameAs(systemProperties);
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE);
// non-string keys and values work fine... until the security manager is introduced below
assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isEqualTo(NON_STRING_PROPERTY_VALUE);
assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME)).isEqualTo(STRING_PROPERTY_VALUE);
// non-string keys and values work fine... until the security manager is introduced below
assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isEqualTo(NON_STRING_PROPERTY_VALUE);
assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME)).isEqualTo(STRING_PROPERTY_VALUE);
}
SecurityManager oldSecurityManager = System.getSecurityManager();
SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPropertiesAccess() {
// see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()
throw new AccessControlException("Accessing the system properties is disallowed");
}
@Override
public void checkPropertyAccess(String key) {
// see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperty(java.lang.String)
if (DISALLOWED_PROPERTY_NAME.equals(key)) {
throw new AccessControlException(
String.format("Accessing the system property [%s] is disallowed", DISALLOWED_PROPERTY_NAME));
}
}
@Override
public void checkPermission(Permission perm) {
// allow everything else
}
};
SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPropertiesAccess() {
// see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()
throw new AccessControlException("Accessing the system properties is disallowed");
}
@Override
public void checkPropertyAccess(String key) {
// see https://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperty(java.lang.String)
if (DISALLOWED_PROPERTY_NAME.equals(key)) {
throw new AccessControlException(
String.format("Accessing the system property [%s] is disallowed", DISALLOWED_PROPERTY_NAME));
}
}
@Override
public void checkPermission(Permission perm) {
// allow everything else
}
};
try {
System.setSecurityManager(securityManager);
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties).isNotNull();
assertThat(systemProperties).isInstanceOf(ReadOnlySystemAttributesMap.class);
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat((String)systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isNull();
// nothing we can do here in terms of warning the user that there was
@@ -349,12 +441,12 @@ class StandardEnvironmentTests {
// the user that under these very special conditions (non-object key +
// SecurityManager that disallows access to system properties), they
// cannot do what they're attempting.
assertThatIllegalArgumentException().as("searching with non-string key against ReadOnlySystemAttributesMap")
.isThrownBy(() -> systemProperties.get(NON_STRING_PROPERTY_NAME));
assertThatIllegalArgumentException().as("searching with non-string key against ReadOnlySystemAttributesMap").isThrownBy(() ->
systemProperties.get(NON_STRING_PROPERTY_NAME));
}
}
finally {
System.setSecurityManager(originalSecurityManager);
System.setSecurityManager(oldSecurityManager);
System.clearProperty(ALLOWED_PROPERTY_NAME);
System.clearProperty(DISALLOWED_PROPERTY_NAME);
System.getProperties().remove(STRING_PROPERTY_NAME);
@@ -407,250 +499,4 @@ class StandardEnvironmentTests {
EnvironmentTestUtils.getModifiableSystemEnvironment().remove(DISALLOWED_PROPERTY_NAME);
}
@Nested
class GetActiveProfiles {
@Test
void systemPropertiesEmpty() {
assertThat(environment.getActiveProfiles()).isEmpty();
try {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "");
assertThat(environment.getActiveProfiles()).isEmpty();
}
finally {
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
}
@Test
void fromSystemProperties() {
try {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo");
assertThat(environment.getActiveProfiles()).containsExactly("foo");
}
finally {
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
}
@Test
void fromSystemProperties_withMultipleProfiles() {
try {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar");
assertThat(environment.getActiveProfiles()).containsExactly("foo", "bar");
}
finally {
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
}
@Test
void fromSystemProperties_withMultipleProfiles_withWhitespace() {
try {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace
assertThat(environment.getActiveProfiles()).containsExactly("bar", "baz");
}
finally {
System.clearProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
}
}
@Nested
class AcceptsProfilesTests {
@Test
@SuppressWarnings("deprecation")
void withEmptyArgumentList() {
assertThatIllegalArgumentException().isThrownBy(environment::acceptsProfiles);
}
@Test
@SuppressWarnings("deprecation")
void withNullArgumentList() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles((String[]) null));
}
@Test
@SuppressWarnings("deprecation")
void withNullArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles((String) null));
}
@Test
@SuppressWarnings("deprecation")
void withEmptyArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles(""));
}
@Test
@SuppressWarnings("deprecation")
void activeProfileSetProgrammatically() {
assertThat(environment.acceptsProfiles("p1", "p2")).isFalse();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p2");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p1", "p2");
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void activeProfileSetViaProperty() {
assertThat(environment.acceptsProfiles("p1")).isFalse();
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void defaultProfile() {
assertThat(environment.acceptsProfiles("pd")).isFalse();
environment.setDefaultProfiles("pd");
assertThat(environment.acceptsProfiles("pd")).isTrue();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("pd")).isFalse();
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void withNotOperator() {
assertThat(environment.acceptsProfiles("p1")).isFalse();
assertThat(environment.acceptsProfiles("!p1")).isTrue();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles("p1")).isTrue();
assertThat(environment.acceptsProfiles("!p1")).isFalse();
}
@Test
@SuppressWarnings("deprecation")
void withInvalidNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.acceptsProfiles("p1", "!"));
}
@Test
void withProfileExpression() {
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p2");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isTrue();
}
}
@Nested
class MatchesProfilesTests {
@Test
@SuppressWarnings("deprecation")
void withEmptyArgumentList() {
assertThatIllegalArgumentException().isThrownBy(environment::matchesProfiles);
}
@Test
@SuppressWarnings("deprecation")
void withNullArgumentList() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles((String[]) null));
}
@Test
@SuppressWarnings("deprecation")
void withNullArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles((String) null));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", null));
}
@Test
@SuppressWarnings("deprecation")
void withEmptyArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles(""));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", ""));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", " "));
}
@Test
@SuppressWarnings("deprecation")
void withInvalidNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", "!"));
}
@Test
@SuppressWarnings("deprecation")
void withInvalidCompoundExpressionGrouping() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1 | p2 & p3"));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1 & p2 | p3"));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1 & (p2 | p3) | p4"));
}
@Test
@SuppressWarnings("deprecation")
void activeProfileSetProgrammatically() {
assertThat(environment.matchesProfiles("p1", "p2")).isFalse();
environment.setActiveProfiles("p1");
assertThat(environment.matchesProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p2");
assertThat(environment.matchesProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p1", "p2");
assertThat(environment.matchesProfiles("p1", "p2")).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void activeProfileSetViaProperty() {
assertThat(environment.matchesProfiles("p1")).isFalse();
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(environment.matchesProfiles("p1")).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void defaultProfile() {
assertThat(environment.matchesProfiles("pd")).isFalse();
environment.setDefaultProfiles("pd");
assertThat(environment.matchesProfiles("pd")).isTrue();
environment.setActiveProfiles("p1");
assertThat(environment.matchesProfiles("pd")).isFalse();
assertThat(environment.matchesProfiles("p1")).isTrue();
}
@Test
@SuppressWarnings("deprecation")
void withNotOperator() {
assertThat(environment.matchesProfiles("p1")).isFalse();
assertThat(environment.matchesProfiles("!p1")).isTrue();
environment.addActiveProfile("p1");
assertThat(environment.matchesProfiles("p1")).isTrue();
assertThat(environment.matchesProfiles("!p1")).isFalse();
}
@Test
void withProfileExpressions() {
assertThat(environment.matchesProfiles("p1 & p2")).isFalse();
environment.addActiveProfile("p1");
assertThat(environment.matchesProfiles("p1 | p2")).isTrue();
assertThat(environment.matchesProfiles("p1 & p2")).isFalse();
environment.addActiveProfile("p2");
assertThat(environment.matchesProfiles("p1 & p2")).isTrue();
assertThat(environment.matchesProfiles("p1 | p2")).isTrue();
assertThat(environment.matchesProfiles("foo | p1", "p2")).isTrue();
assertThat(environment.matchesProfiles("foo | p2", "p1")).isTrue();
assertThat(environment.matchesProfiles("foo | (p2 & p1)")).isTrue();
assertThat(environment.matchesProfiles("p2 & (foo | p1)")).isTrue();
assertThat(environment.matchesProfiles("foo", "(p2 & p1)")).isTrue();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,40 +16,16 @@
package org.springframework.util;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.springframework.util.ObjectUtils.isEmpty;
@@ -237,7 +213,7 @@ class ObjectUtilsTests {
}
@Test
void addObjectToNullArray() {
void addObjectToNullArray() throws Exception {
String newElement = "foo";
String[] newArray = ObjectUtils.addObjectToArray(null, newElement);
assertThat(newArray).hasSize(1);
@@ -245,14 +221,14 @@ class ObjectUtilsTests {
}
@Test
void addNullObjectToNullArray() {
void addNullObjectToNullArray() throws Exception {
Object[] newArray = ObjectUtils.addObjectToArray(null, null);
assertThat(newArray).hasSize(1);
assertThat(newArray[0]).isNull();
}
@Test
void nullSafeEqualsWithArrays() {
void nullSafeEqualsWithArrays() throws Exception {
assertThat(ObjectUtils.nullSafeEquals(new String[] {"a", "b", "c"}, new String[] {"a", "b", "c"})).isTrue();
assertThat(ObjectUtils.nullSafeEquals(new int[] {1, 2, 3}, new int[] {1, 2, 3})).isTrue();
}
@@ -840,304 +816,13 @@ class ObjectUtilsTests {
.withMessage("Constant [bogus] does not exist in enum type org.springframework.util.ObjectUtilsTests$Tropes");
}
private static void assertEqualHashCodes(int expected, Object array) {
private void assertEqualHashCodes(int expected, Object array) {
int actual = ObjectUtils.nullSafeHashCode(array);
assertThat(actual).isEqualTo(expected);
assertThat(array.hashCode()).isNotEqualTo(actual);
assertThat(array.hashCode() != actual).isTrue();
}
enum Tropes {FOO, BAR, baz}
@Nested
class NullSafeConciseToStringTests {
private final String truncated = " (truncated)...";
private final int truncatedLength = 100 + truncated.length();
@Test
void nullSafeConciseToStringForNull() {
assertThat(ObjectUtils.nullSafeConciseToString(null)).isEqualTo("null");
}
@Test
void nullSafeConciseToStringForEmptyOptional() {
Optional<String> optional = Optional.empty();
assertThat(ObjectUtils.nullSafeConciseToString(optional)).isEqualTo("Optional.empty");
}
@Test
void nullSafeConciseToStringForNonEmptyOptionals() {
Optional<Tropes> optionalEnum = Optional.of(Tropes.BAR);
String expected = "Optional[BAR]";
assertThat(ObjectUtils.nullSafeConciseToString(optionalEnum)).isEqualTo(expected);
String repeat100 = repeat("X", 100);
String repeat101 = repeat("X", 101);
Optional<String> optionalString = Optional.of(repeat100);
expected = String.format("Optional[%s]", repeat100);
assertThat(ObjectUtils.nullSafeConciseToString(optionalString)).isEqualTo(expected);
optionalString = Optional.of(repeat101);
expected = String.format("Optional[%s]", repeat100 + truncated);
assertThat(ObjectUtils.nullSafeConciseToString(optionalString)).isEqualTo(expected);
}
@Test
void nullSafeConciseToStringForNonEmptyOptionalCustomType() {
class CustomType {
}
CustomType customType = new CustomType();
Optional<CustomType> optional = Optional.of(customType);
String expected = String.format("Optional[%s]", ObjectUtils.nullSafeConciseToString(customType));
assertThat(ObjectUtils.nullSafeConciseToString(optional)).isEqualTo(expected);
}
@Test
void nullSafeConciseToStringForClass() {
assertThat(ObjectUtils.nullSafeConciseToString(String.class)).isEqualTo("java.lang.String");
}
@Test
void nullSafeConciseToStringForStrings() {
String repeat100 = repeat("X", 100);
String repeat101 = repeat("X", 101);
assertThat(ObjectUtils.nullSafeConciseToString("")).isEqualTo("");
assertThat(ObjectUtils.nullSafeConciseToString("foo")).isEqualTo("foo");
assertThat(ObjectUtils.nullSafeConciseToString(repeat100)).isEqualTo(repeat100);
assertThat(ObjectUtils.nullSafeConciseToString(repeat101)).hasSize(truncatedLength).endsWith(truncated);
}
@Test
void nullSafeConciseToStringForStringBuilders() {
String repeat100 = repeat("X", 100);
String repeat101 = repeat("X", 101);
assertThat(ObjectUtils.nullSafeConciseToString(new StringBuilder("foo"))).isEqualTo("foo");
assertThat(ObjectUtils.nullSafeConciseToString(new StringBuilder(repeat100))).isEqualTo(repeat100);
assertThat(ObjectUtils.nullSafeConciseToString(new StringBuilder(repeat101))).hasSize(truncatedLength).endsWith(truncated);
}
@Test
void nullSafeConciseToStringForEnum() {
assertThat(ObjectUtils.nullSafeConciseToString(Tropes.FOO)).isEqualTo("FOO");
}
@Test
void nullSafeConciseToStringForPrimitivesAndWrappers() {
assertThat(ObjectUtils.nullSafeConciseToString(true)).isEqualTo("true");
assertThat(ObjectUtils.nullSafeConciseToString('X')).isEqualTo("X");
assertThat(ObjectUtils.nullSafeConciseToString(42L)).isEqualTo("42");
assertThat(ObjectUtils.nullSafeConciseToString(99.1234D)).isEqualTo("99.1234");
}
@Test
void nullSafeConciseToStringForBigNumbers() {
assertThat(ObjectUtils.nullSafeConciseToString(BigInteger.valueOf(42L))).isEqualTo("42");
assertThat(ObjectUtils.nullSafeConciseToString(BigDecimal.valueOf(99.1234D))).isEqualTo("99.1234");
}
@Test
void nullSafeConciseToStringForDate() {
Date date = new Date();
assertThat(ObjectUtils.nullSafeConciseToString(date)).isEqualTo(date.toString());
}
@Test
void nullSafeConciseToStringForTemporal() {
LocalDate localDate = LocalDate.now();
assertThat(ObjectUtils.nullSafeConciseToString(localDate)).isEqualTo(localDate.toString());
}
@Test
void nullSafeConciseToStringForUUID() {
UUID id = UUID.randomUUID();
assertThat(ObjectUtils.nullSafeConciseToString(id)).isEqualTo(id.toString());
}
@Test
void nullSafeConciseToStringForFile() {
String path = "/tmp/file.txt".replace('/', File.separatorChar);
assertThat(ObjectUtils.nullSafeConciseToString(new File(path))).isEqualTo(path);
path = ("/tmp/" + repeat("xyz", 32)).replace('/', File.separatorChar);
assertThat(ObjectUtils.nullSafeConciseToString(new File(path)))
.hasSize(truncatedLength)
.startsWith(path.subSequence(0, 100))
.endsWith(truncated);
}
@Test
void nullSafeConciseToStringForPath() {
String path = "/tmp/file.txt".replace('/', File.separatorChar);
assertThat(ObjectUtils.nullSafeConciseToString(Paths.get(path))).isEqualTo(path);
path = ("/tmp/" + repeat("xyz", 32)).replace('/', File.separatorChar);
assertThat(ObjectUtils.nullSafeConciseToString(Paths.get(path)))
.hasSize(truncatedLength)
.startsWith(path.subSequence(0, 100))
.endsWith(truncated);
}
@Test
void nullSafeConciseToStringForURI() {
String uri = "https://www.example.com/?foo=1&bar=2&baz=3";
assertThat(ObjectUtils.nullSafeConciseToString(URI.create(uri))).isEqualTo(uri);
uri += "&qux=" + repeat("4", 60);
assertThat(ObjectUtils.nullSafeConciseToString(URI.create(uri)))
.hasSize(truncatedLength)
.startsWith(uri.subSequence(0, 100))
.endsWith(truncated);
}
@Test
void nullSafeConciseToStringForURL() throws Exception {
String url = "https://www.example.com/?foo=1&bar=2&baz=3";
assertThat(ObjectUtils.nullSafeConciseToString(new URL(url))).isEqualTo(url);
url += "&qux=" + repeat("4", 60);
assertThat(ObjectUtils.nullSafeConciseToString(new URL(url)))
.hasSize(truncatedLength)
.startsWith(url.subSequence(0, 100))
.endsWith(truncated);
}
@Test
void nullSafeConciseToStringForInetAddress() {
InetAddress localhost = getLocalhost();
assertThat(ObjectUtils.nullSafeConciseToString(localhost)).isEqualTo(localhost.toString());
}
private InetAddress getLocalhost() {
try {
return InetAddress.getLocalHost();
}
catch (UnknownHostException ex) {
return InetAddress.getLoopbackAddress();
}
}
@Test
void nullSafeConciseToStringForCharset() {
Charset charset = StandardCharsets.UTF_8;
assertThat(ObjectUtils.nullSafeConciseToString(charset)).isEqualTo(charset.name());
}
@Test
void nullSafeConciseToStringForCurrency() {
Currency currency = Currency.getInstance(Locale.US);
assertThat(ObjectUtils.nullSafeConciseToString(currency)).isEqualTo(currency.toString());
}
@Test
void nullSafeConciseToStringForLocale() {
assertThat(ObjectUtils.nullSafeConciseToString(Locale.GERMANY)).isEqualTo("de_DE");
}
@Test
void nullSafeConciseToStringForRegExPattern() {
Pattern pattern = Pattern.compile("^(foo|bar)$");
assertThat(ObjectUtils.nullSafeConciseToString(pattern)).isEqualTo(pattern.toString());
}
@Test
void nullSafeConciseToStringForTimeZone() {
TimeZone timeZone = TimeZone.getDefault();
assertThat(ObjectUtils.nullSafeConciseToString(timeZone)).isEqualTo(timeZone.getID());
}
@Test
void nullSafeConciseToStringForZoneId() {
ZoneId zoneId = ZoneId.systemDefault();
assertThat(ObjectUtils.nullSafeConciseToString(zoneId)).isEqualTo(zoneId.getId());
}
@Test
void nullSafeConciseToStringForEmptyArrays() {
assertThat(ObjectUtils.nullSafeConciseToString(new char[] {})).isEqualTo("{}");
assertThat(ObjectUtils.nullSafeConciseToString(new int[][] {})).isEqualTo("{}");
assertThat(ObjectUtils.nullSafeConciseToString(new String[] {})).isEqualTo("{}");
assertThat(ObjectUtils.nullSafeConciseToString(new Integer[][] {})).isEqualTo("{}");
}
@Test
void nullSafeConciseToStringForNonEmptyArrays() {
assertThat(ObjectUtils.nullSafeConciseToString(new char[] {'a'})).isEqualTo("{...}");
assertThat(ObjectUtils.nullSafeConciseToString(new int[][] {{1}, {2}})).isEqualTo("{...}");
assertThat(ObjectUtils.nullSafeConciseToString(new String[] {"enigma"})).isEqualTo("{...}");
assertThat(ObjectUtils.nullSafeConciseToString(new Integer[][] {{1}, {2}})).isEqualTo("{...}");
}
@Test
void nullSafeConciseToStringForEmptyCollections() {
List<String> list = Collections.emptyList();
Set<Integer> set = Collections.emptySet();
assertThat(ObjectUtils.nullSafeConciseToString(list)).isEqualTo("[]");
assertThat(ObjectUtils.nullSafeConciseToString(set)).isEqualTo("[]");
}
@Test
void nullSafeConciseToStringForNonEmptyCollections() {
List<String> list = Arrays.asList("a", "b");
Set<String> set = new HashSet<>();
set.add("foo");
assertThat(ObjectUtils.nullSafeConciseToString(list)).isEqualTo("[...]");
assertThat(ObjectUtils.nullSafeConciseToString(set)).isEqualTo("[...]");
}
@Test
void nullSafeConciseToStringForEmptyMaps() {
Map<String, Object> map = Collections.emptyMap();
assertThat(ObjectUtils.nullSafeConciseToString(map)).isEqualTo("{}");
}
@Test
void nullSafeConciseToStringForNonEmptyMaps() {
HashMap<String, Object> map = new HashMap<>();
map.put("foo", 42L);
assertThat(ObjectUtils.nullSafeConciseToString(map)).isEqualTo("{...}");
}
@Test
void nullSafeConciseToStringForCustomTypes() {
class ExplosiveType {
@Override
public String toString() {
throw new UnsupportedOperationException("no-go");
}
}
ExplosiveType explosiveType = new ExplosiveType();
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(explosiveType::toString);
assertThat(ObjectUtils.nullSafeConciseToString(explosiveType)).startsWith(prefix(ExplosiveType.class));
class WordyType {
@Override
public String toString() {
return repeat("blah blah", 20);
}
}
WordyType wordyType = new WordyType();
assertThat(wordyType).asString().hasSizeGreaterThanOrEqualTo(180 /* 9x20 */);
assertThat(ObjectUtils.nullSafeConciseToString(wordyType)).startsWith(prefix(WordyType.class));
}
private String repeat(String str, int count) {
String result = "";
for (int i = 0; i < count; i++) {
result += str;
}
return result;
}
private String prefix(Class<?> clazz) {
return clazz.getTypeName() + "@";
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,6 @@ import java.util.Locale;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -787,26 +785,4 @@ class StringUtilsTests {
assertThat(StringUtils.collectionToCommaDelimitedString(Collections.singletonList(null))).isEqualTo("null");
}
@Test
void truncatePreconditions() {
assertThatIllegalArgumentException()
.isThrownBy(() -> StringUtils.truncate("foo", 0))
.withMessage("Truncation threshold must be a positive number: 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> StringUtils.truncate("foo", -99))
.withMessage("Truncation threshold must be a positive number: -99");
}
@ParameterizedTest
@CsvSource(delimiterString = "-->", value = {
"'' --> ''",
"aardvark --> aardvark",
"aardvark12 --> aardvark12",
"aardvark123 --> aardvark12 (truncated)...",
"aardvark, bird, cat --> aardvark, (truncated)..."
})
void truncate(String text, String truncated) {
assertThat(StringUtils.truncate(text, 10)).isEqualTo(truncated);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.expression;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.lang.Nullable;
@@ -25,21 +24,12 @@ import org.springframework.lang.Nullable;
* Expressions are executed in an evaluation context. It is in this context that
* references are resolved when encountered during expression evaluation.
*
* <p>There are two default implementations of this interface.
* <ul>
* <li>{@link org.springframework.expression.spel.support.SimpleEvaluationContext
* SimpleEvaluationContext}: a simpler builder-style {@code EvaluationContext}
* variant for data-binding purposes, which allows for opting into several SpEL
* features as needed.</li>
* <li>{@link org.springframework.expression.spel.support.StandardEvaluationContext
* StandardEvaluationContext}: a powerful and highly configurable {@code EvaluationContext}
* implementation, which can be extended, rather than having to implement everything
* manually.</li>
* </ul>
* <p>There is a default implementation of this EvaluationContext interface:
* {@link org.springframework.expression.spel.support.StandardEvaluationContext}
* which can be extended, rather than having to implement everything manually.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
*/
public interface EvaluationContext {
@@ -95,30 +85,7 @@ public interface EvaluationContext {
OperatorOverloader getOperatorOverloader();
/**
* Assign the value created by the specified {@link Supplier} to a named variable
* within this evaluation context.
* <p>In contrast to {@link #setVariable(String, Object)}, this method should only
* be invoked to support the assignment operator ({@code =}) within an expression.
* <p>By default, this method delegates to {@code setVariable(String, Object)},
* providing the value created by the {@code valueSupplier}. Concrete implementations
* may override this <em>default</em> method to provide different semantics.
* @param name the name of the variable to assign
* @param valueSupplier the supplier of the value to be assigned to the variable
* @return a {@link TypedValue} wrapping the assigned value
* @since 5.2.24
*/
default TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
TypedValue typedValue = valueSupplier.get();
setVariable(name, typedValue.getValue());
return typedValue;
}
/**
* Set a named variable in this evaluation context to a specified value.
* <p>In contrast to {@link #assignVariable(String, Supplier)}, this method
* should only be invoked programmatically when interacting directly with the
* {@code EvaluationContext} &mdash; for example, to provide initial
* configuration for the context.
* Set a named variable within this evaluation context to a specified value.
* @param name the name of the variable to set
* @param value the value to be placed in the variable
*/
@@ -126,7 +93,7 @@ public interface EvaluationContext {
/**
* Look up a named variable within this evaluation context.
* @param name the name of the variable to look up
* @param name variable to lookup
* @return the value of the variable, or {@code null} if not found
*/
@Nullable
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +26,6 @@ import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParseException;
import org.springframework.expression.ParserContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* An expression parser that understands templates. It can be subclassed by expression
@@ -35,7 +34,6 @@ import org.springframework.util.Assert;
* @author Keith Donald
* @author Juergen Hoeller
* @author Andy Clement
* @author Sam Brannen
* @since 3.0
*/
public abstract class TemplateAwareExpressionParser implements ExpressionParser {
@@ -48,11 +46,9 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
@Override
public Expression parseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
if (context != null && context.isTemplate()) {
Assert.notNull(expressionString, "'expressionString' must not be null");
return parseTemplate(expressionString, context);
}
else {
Assert.hasText(expressionString, "'expressionString' must not be null or blank");
return doParseExpression(expressionString, context);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Supplier;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.EvaluationContext;
@@ -39,19 +38,18 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* ExpressionState is for maintaining per-expression-evaluation state: any changes to
* it are not seen by other expressions, but it gives a place to hold local variables and
* An ExpressionState is for maintaining per-expression-evaluation state, any changes to
* it are not seen by other expressions but it gives a place to hold local variables and
* for component expressions in a compound expression to communicate state. This is in
* contrast to the EvaluationContext, which is shared amongst expression evaluations, and
* any changes to it will be seen by other expressions or any code that chooses to ask
* questions of the context.
*
* <p>It also acts as a place to define common utility routines that the various AST
* <p>It also acts as a place for to define common utility routines that the various AST
* nodes might need.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
*/
public class ExpressionState {
@@ -140,29 +138,6 @@ public class ExpressionState {
return this.scopeRootObjects.element();
}
/**
* Assign the value created by the specified {@link Supplier} to a named variable
* within the evaluation context.
* <p>In contrast to {@link #setVariable(String, Object)}, this method should
* only be invoked to support assignment within an expression.
* @param name the name of the variable to assign
* @param valueSupplier the supplier of the value to be assigned to the variable
* @return a {@link TypedValue} wrapping the assigned value
* @since 5.2.24
* @see EvaluationContext#assignVariable(String, Supplier)
*/
public TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
return this.relatedContext.assignVariable(name, valueSupplier);
}
/**
* Set a named variable in the evaluation context to a specified value.
* <p>In contrast to {@link #assignVariable(String, Supplier)}, this method
* should only be invoked programmatically.
* @param name the name of the variable to set
* @param value the value to be placed in the variable
* @see EvaluationContext#setVariable(String, Object)
*/
public void setVariable(String name, @Nullable Object value) {
this.relatedContext.setVariable(name, value);
}
@@ -266,25 +266,13 @@ public enum SpelMessage {
MAX_ARRAY_ELEMENTS_THRESHOLD_EXCEEDED(Kind.ERROR, 1075,
"Array declares too many elements, exceeding the threshold of ''{0}''"),
/** @since 5.2.23 */
/** @since 5.3.26 */
MAX_REPEATED_TEXT_SIZE_EXCEEDED(Kind.ERROR, 1076,
"Repeated text is too long, exceeding the threshold of ''{0}'' characters"),
"Repeated text results in too many characters, exceeding the threshold of ''{0}''"),
/** @since 5.2.23 */
/** @since 5.3.26 */
MAX_REGEX_LENGTH_EXCEEDED(Kind.ERROR, 1077,
"Regular expression is too long, exceeding the threshold of ''{0}'' characters"),
/** @since 5.2.24 */
MAX_CONCATENATED_STRING_LENGTH_EXCEEDED(Kind.ERROR, 1078,
"Concatenated string is too long, exceeding the threshold of ''{0}'' characters"),
/** @since 5.2.24 */
MAX_EXPRESSION_LENGTH_EXCEEDED(Kind.ERROR, 1079,
"SpEL expression is too long, exceeding the threshold of ''{0}'' characters"),
/** @since 5.2.24 */
VARIABLE_ASSIGNMENT_NOT_SUPPORTED(Kind.ERROR, 1080,
"Assignment to variable ''{0}'' is not supported");
"Regular expression contains too many characters, exceeding the threshold of ''{0}''");
private final Kind kind;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,12 +30,6 @@ import org.springframework.lang.Nullable;
*/
public class SpelParserConfiguration {
/**
* Default maximum length permitted for a SpEL expression.
* @since 5.2.24
*/
private static final int DEFAULT_MAX_EXPRESSION_LENGTH = 10_000;
/** System property to configure the default compiler mode for SpEL expression parsers: {@value}. */
public static final String SPRING_EXPRESSION_COMPILER_MODE_PROPERTY_NAME = "spring.expression.compiler.mode";
@@ -60,8 +54,6 @@ public class SpelParserConfiguration {
private final int maximumAutoGrowSize;
private final int maximumExpressionLength;
/**
* Create a new {@code SpelParserConfiguration} instance with default settings.
@@ -110,30 +102,11 @@ public class SpelParserConfiguration {
public SpelParserConfiguration(@Nullable SpelCompilerMode compilerMode, @Nullable ClassLoader compilerClassLoader,
boolean autoGrowNullReferences, boolean autoGrowCollections, int maximumAutoGrowSize) {
this(compilerMode, compilerClassLoader, autoGrowNullReferences, autoGrowCollections,
maximumAutoGrowSize, DEFAULT_MAX_EXPRESSION_LENGTH);
}
/**
* Create a new {@code SpelParserConfiguration} instance.
* @param compilerMode the compiler mode that parsers using this configuration object should use
* @param compilerClassLoader the ClassLoader to use as the basis for expression compilation
* @param autoGrowNullReferences if null references should automatically grow
* @param autoGrowCollections if collections should automatically grow
* @param maximumAutoGrowSize the maximum size that a collection can auto grow
* @param maximumExpressionLength the maximum length of a SpEL expression;
* must be a positive number
* @since 5.2.25
*/
public SpelParserConfiguration(@Nullable SpelCompilerMode compilerMode, @Nullable ClassLoader compilerClassLoader,
boolean autoGrowNullReferences, boolean autoGrowCollections, int maximumAutoGrowSize, int maximumExpressionLength) {
this.compilerMode = (compilerMode != null ? compilerMode : defaultCompilerMode);
this.compilerClassLoader = compilerClassLoader;
this.autoGrowNullReferences = autoGrowNullReferences;
this.autoGrowCollections = autoGrowCollections;
this.maximumAutoGrowSize = maximumAutoGrowSize;
this.maximumExpressionLength = maximumExpressionLength;
}
@@ -173,12 +146,4 @@ public class SpelParserConfiguration {
return this.maximumAutoGrowSize;
}
/**
* Return the maximum number of characters that a SpEL expression can contain.
* @since 5.2.25
*/
public int getMaximumExpressionLength() {
return this.maximumExpressionLength;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,6 @@ import org.springframework.expression.spel.ExpressionState;
* <p>Example: 'someNumberProperty=42'
*
* @author Andy Clement
* @author Sam Brannen
* @since 3.0
*/
public class Assign extends SpelNodeImpl {
@@ -39,7 +38,9 @@ public class Assign extends SpelNodeImpl {
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
return this.children[0].setValueInternal(state, () -> this.children[1].getValueInternal(state));
TypedValue newValue = this.children[1].getValueInternal(state);
getChild(0).setValue(state, newValue.getValue());
return newValue;
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.expression.spel.ast;
import java.util.StringJoiner;
import java.util.function.Supplier;
import org.springframework.asm.MethodVisitor;
import org.springframework.expression.EvaluationException;
@@ -25,13 +24,13 @@ import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.lang.Nullable;
/**
* Represents a DOT separated expression sequence, such as
* {@code 'property1.property2.methodOne()'}.
*
* @author Andy Clement
* @author Sam Brannen
* @since 3.0
*/
public class CompoundExpression extends SpelNodeImpl {
@@ -96,12 +95,8 @@ public class CompoundExpression extends SpelNodeImpl {
}
@Override
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
throws EvaluationException {
TypedValue typedValue = valueSupplier.get();
getValueRef(state).setValue(typedValue.getValue());
return typedValue;
public void setValue(ExpressionState state, @Nullable Object value) throws EvaluationException {
getValueRef(state).setValue(value);
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,6 @@ import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.function.Supplier;
import org.springframework.asm.MethodVisitor;
import org.springframework.core.convert.TypeDescriptor;
@@ -46,12 +45,11 @@ import org.springframework.util.ReflectionUtils;
/**
* An Indexer can index into some proceeding structure to access a particular piece of it.
* <p>Supported structures are: strings / collections (lists/sets) / arrays.
* Supported structures are: strings / collections (lists/sets) / arrays.
*
* @author Andy Clement
* @author Phillip Webb
* @author Stephane Nicoll
* @author Sam Brannen
* @since 3.0
*/
// TODO support multidimensional arrays
@@ -104,12 +102,8 @@ public class Indexer extends SpelNodeImpl {
}
@Override
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
throws EvaluationException {
TypedValue typedValue = valueSupplier.get();
getValueRef(state).setValue(typedValue.getValue());
return typedValue;
public void setValue(ExpressionState state, @Nullable Object newValue) throws EvaluationException {
getValueRef(state).setValue(newValue);
}
@Override
@@ -56,7 +56,7 @@ public class OpMultiply extends Operator {
/**
* Maximum number of characters permitted in repeated text.
* @since 5.2.23
* @since 5.3.26
*/
private static final int MAX_REPEATED_TEXT_SIZE = 256;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,8 +27,6 @@ import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.NumberUtils;
@@ -48,18 +46,10 @@ import org.springframework.util.NumberUtils;
* @author Juergen Hoeller
* @author Ivo Smid
* @author Giovanni Dall'Oglio Risso
* @author Sam Brannen
* @since 3.0
*/
public class OpPlus extends Operator {
/**
* Maximum number of characters permitted in a concatenated string.
* @since 5.2.24
*/
private static final int MAX_CONCATENATED_STRING_LENGTH = 100_000;
public OpPlus(int startPos, int endPos, SpelNodeImpl... operands) {
super("+", startPos, endPos, operands);
Assert.notEmpty(operands, "Operands must not be empty");
@@ -133,45 +123,22 @@ public class OpPlus extends Operator {
if (leftOperand instanceof String && rightOperand instanceof String) {
this.exitTypeDescriptor = "Ljava/lang/String";
String leftString = (String) leftOperand;
String rightString = (String) rightOperand;
checkStringLength(leftString);
checkStringLength(rightString);
return concatenate(leftString, rightString);
return new TypedValue((String) leftOperand + rightOperand);
}
if (leftOperand instanceof String) {
String leftString = (String) leftOperand;
checkStringLength(leftString);
String rightString = (rightOperand == null ? "null" : convertTypedValueToString(operandTwoValue, state));
checkStringLength(rightString);
return concatenate(leftString, rightString);
return new TypedValue(
leftOperand + (rightOperand == null ? "null" : convertTypedValueToString(operandTwoValue, state)));
}
if (rightOperand instanceof String) {
String rightString = (String) rightOperand;
checkStringLength(rightString);
String leftString = (leftOperand == null ? "null" : convertTypedValueToString(operandOneValue, state));
checkStringLength(leftString);
return concatenate(leftString, rightString);
return new TypedValue(
(leftOperand == null ? "null" : convertTypedValueToString(operandOneValue, state)) + rightOperand);
}
return state.operate(Operation.ADD, leftOperand, rightOperand);
}
private void checkStringLength(String string) {
if (string.length() > MAX_CONCATENATED_STRING_LENGTH) {
throw new SpelEvaluationException(getStartPosition(),
SpelMessage.MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, MAX_CONCATENATED_STRING_LENGTH);
}
}
private TypedValue concatenate(String leftString, String rightString) {
String result = leftString + rightString;
checkStringLength(result);
return new TypedValue(result);
}
@Override
public String toStringAST() {
if (this.children.length < 2) { // unary plus
@@ -45,16 +45,16 @@ public class OperatorMatches extends Operator {
/**
* Maximum number of characters permitted in a regular expression.
* @since 5.2.23
* @since 5.3.26
*/
private static final int MAX_REGEX_LENGTH = 1000;
private static final int MAX_REGEX_LENGTH = 256;
private final ConcurrentMap<String, Pattern> patternCache;
/**
* Create a new {@link OperatorMatches} instance.
* @deprecated as of Spring Framework 5.2.23 in favor of invoking
* @deprecated as of Spring Framework 5.3.26 in favor of invoking
* {@link #OperatorMatches(ConcurrentMap, int, int, SpelNodeImpl...)}
* with a shared pattern cache instead
*/
@@ -65,7 +65,7 @@ public class OperatorMatches extends Operator {
/**
* Create a new {@link OperatorMatches} instance with a shared pattern cache.
* @since 5.2.23
* @since 5.3.26
*/
public OperatorMatches(ConcurrentMap<String, Pattern> patternCache, int startPos, int endPos, SpelNodeImpl... operands) {
super("matches", startPos, endPos, operands);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.springframework.asm.Label;
import org.springframework.asm.MethodVisitor;
@@ -47,7 +46,6 @@ import org.springframework.util.ReflectionUtils;
* @author Andy Clement
* @author Juergen Hoeller
* @author Clark Duplichien
* @author Sam Brannen
* @since 3.0
*/
public class PropertyOrFieldReference extends SpelNodeImpl {
@@ -149,12 +147,8 @@ public class PropertyOrFieldReference extends SpelNodeImpl {
}
@Override
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
throws EvaluationException {
TypedValue typedValue = valueSupplier.get();
writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, typedValue.getValue());
return typedValue;
public void setValue(ExpressionState state, @Nullable Object newValue) throws EvaluationException {
writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, newValue);
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.expression.spel.ast;
import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import org.springframework.asm.MethodVisitor;
import org.springframework.asm.Opcodes;
@@ -41,7 +40,6 @@ import org.springframework.util.ObjectUtils;
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
*/
public abstract class SpelNodeImpl implements SpelNode, Opcodes {
@@ -66,7 +64,7 @@ public abstract class SpelNodeImpl implements SpelNode, Opcodes {
* <p>The descriptor is like the bytecode form but is slightly easier to work with.
* It does not include the trailing semicolon (for non array reference types).
* Some examples: Ljava/lang/String, I, [I
*/
*/
@Nullable
protected volatile String exitTypeDescriptor;
@@ -85,8 +83,8 @@ public abstract class SpelNodeImpl implements SpelNode, Opcodes {
/**
* Return {@code true} if the next child is one of the specified classes.
*/
* Return {@code true} if the next child is one of the specified classes.
*/
protected boolean nextChildIs(Class<?>... classes) {
if (this.parent != null) {
SpelNodeImpl[] peers = this.parent.children;
@@ -127,28 +125,6 @@ public abstract class SpelNodeImpl implements SpelNode, Opcodes {
@Override
public void setValue(ExpressionState expressionState, @Nullable Object newValue) throws EvaluationException {
setValueInternal(expressionState, () -> new TypedValue(newValue));
}
/**
* Evaluate the expression to a node and then set the new value created by the
* specified {@link Supplier} on that node.
* <p>For example, if the expression evaluates to a property reference, then the
* property will be set to the new value.
* <p>Favor this method over {@link #setValue(ExpressionState, Object)} when
* the value should be lazily computed.
* <p>By default, this method throws a {@link SpelEvaluationException},
* effectively disabling this feature. Subclasses may override this method to
* provide an actual implementation.
* @param expressionState the current expression state (includes the context)
* @param valueSupplier a supplier of the new value
* @throws EvaluationException if any problem occurs evaluating the expression or
* setting the new value
* @since 5.2.24
*/
public TypedValue setValueInternal(ExpressionState expressionState, Supplier<TypedValue> valueSupplier)
throws EvaluationException {
throw new SpelEvaluationException(getStartPosition(), SpelMessage.SETVALUE_NOT_SUPPORTED, getClass());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,11 +17,9 @@
package org.springframework.expression.spel.ast;
import java.lang.reflect.Modifier;
import java.util.function.Supplier;
import org.springframework.asm.MethodVisitor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
@@ -29,11 +27,10 @@ import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.lang.Nullable;
/**
* Represents a variable reference &mdash; for example, {@code #someVar}. Note
* that this is different than a <em>local</em> variable like {@code $someVar}.
* Represents a variable reference, eg. #someVar. Note this is different to a *local*
* variable like $someVar
*
* @author Andy Clement
* @author Sam Brannen
* @since 3.0
*/
public class VariableReference extends SpelNodeImpl {
@@ -56,14 +53,14 @@ public class VariableReference extends SpelNodeImpl {
@Override
public ValueRef getValueRef(ExpressionState state) throws SpelEvaluationException {
if (this.name.equals(THIS)) {
return new ValueRef.TypedValueHolderValueRef(state.getActiveContextObject(), this);
return new ValueRef.TypedValueHolderValueRef(state.getActiveContextObject(),this);
}
if (this.name.equals(ROOT)) {
return new ValueRef.TypedValueHolderValueRef(state.getRootContextObject(), this);
return new ValueRef.TypedValueHolderValueRef(state.getRootContextObject(),this);
}
TypedValue result = state.lookupVariable(this.name);
// a null value will mean either the value was null or the variable was not found
return new VariableRef(this.name, result, state.getEvaluationContext());
return new VariableRef(this.name,result,state.getEvaluationContext());
}
@Override
@@ -93,10 +90,8 @@ public class VariableReference extends SpelNodeImpl {
}
@Override
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
throws EvaluationException {
return state.assignVariable(this.name, valueSupplier);
public void setValue(ExpressionState state, @Nullable Object value) throws SpelEvaluationException {
state.setVariable(this.name, value);
}
@Override

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