mirror of
https://github.com/spring-projects/spring-framework
synced 2026-06-08 17:33:33 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 08bc1a050e |
+1
-3
@@ -46,6 +46,4 @@ atlassian-ide-plugin.xml
|
||||
.gradletasknamecache
|
||||
|
||||
# VS Code
|
||||
.vscode/
|
||||
|
||||
cached-antora-playbook.yml
|
||||
.vscode/
|
||||
@@ -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
|
||||
|
||||
+6
-6
@@ -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.93.Final"
|
||||
mavenBom "io.projectreactor:reactor-bom:2020.0.33"
|
||||
mavenBom "io.netty:netty-bom:4.1.91.Final"
|
||||
mavenBom "io.projectreactor:reactor-bom:2020.0.31"
|
||||
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.75') {
|
||||
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.75') {
|
||||
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.24.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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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" ]
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
version=5.3.28
|
||||
version=5.3.27
|
||||
org.gradle.jvmargs=-Xmx2048m
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
|
||||
+4
-3
@@ -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"
|
||||
|
||||
+29
-26
@@ -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} > 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 <returningName>.</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:
|
||||
* @this, @target, @args, @within, @withincode, @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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,33 +123,12 @@ 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 == null || classLoader.getParent() == null) {
|
||||
// JDK bootstrap loader or platform loader suggested ->
|
||||
// use higher-level loader which can see Spring infrastructure classes
|
||||
classLoader = 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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+3
-9
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-14
@@ -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
-2
@@ -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;
|
||||
|
||||
+3
-2
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-7
@@ -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.
|
||||
|
||||
@@ -388,8 +388,7 @@ public class ProxyFactoryTests {
|
||||
CharSequence target = "test";
|
||||
ProxyFactory pf = new ProxyFactory(target);
|
||||
ClassLoader cl = target.getClass().getClassLoader();
|
||||
CharSequence proxy = (CharSequence) pf.getProxy(cl);
|
||||
assertThat(proxy.toString()).isEqualTo(target);
|
||||
assertThat(((CharSequence) pf.getProxy(cl)).toString()).isEqualTo(target);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -398,8 +397,7 @@ public class ProxyFactoryTests {
|
||||
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());
|
||||
assertThat(((Date) pf.getProxy(cl)).getTime()).isEqualTo(target.getTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -416,8 +414,7 @@ public class ProxyFactoryTests {
|
||||
};
|
||||
ProxyFactory pf = new ProxyFactory(target);
|
||||
ClassLoader cl = Savepoint.class.getClassLoader();
|
||||
Savepoint proxy = (Savepoint) pf.getProxy(cl);
|
||||
assertThat(proxy.getSavepointName()).isEqualTo("sp");
|
||||
assertThat(((Savepoint) pf.getProxy(cl)).getSavepointName()).isEqualTo("sp");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+3
-3
@@ -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.
|
||||
@@ -665,7 +665,7 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
|
||||
if (value != null || this.required) {
|
||||
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())) {
|
||||
@@ -778,7 +778,7 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
|
||||
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]);
|
||||
|
||||
+4
-4
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+1
-1
@@ -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
-21
@@ -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.
|
||||
@@ -133,26 +133,6 @@ public class AutowiredAnnotationBeanPostProcessorTests {
|
||||
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);
|
||||
|
||||
NonPublicResourceInjectionBean bean = (NonPublicResourceInjectionBean) bf.getBean("annotatedBean");
|
||||
assertThat(bean.getTestBean()).isNull();
|
||||
assertThat(bean.getTestBean2()).isNull();
|
||||
assertThat(bean.getTestBean3()).isNull();
|
||||
|
||||
bean = (NonPublicResourceInjectionBean) 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);
|
||||
|
||||
+4
-5
@@ -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
-7
@@ -274,7 +274,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
|
||||
handleAsyncError(ex);
|
||||
}
|
||||
else if (event != null) {
|
||||
publishEvents(event);
|
||||
publishEvent(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+1
-10
@@ -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 — 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 — 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 — 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 "";
|
||||
|
||||
|
||||
+3
-11
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+6
-5
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+4
-6
@@ -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
|
||||
@@ -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
|
||||
|
||||
+7
-44
@@ -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();
|
||||
|
||||
+3
-16
@@ -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 {
|
||||
|
||||
+3
-36
@@ -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,40 +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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 or more of the given profiles is active — 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 one of the given profile expressions matches the
|
||||
* {@linkplain #getActiveProfiles() active profiles} — 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 — 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 the given {@link Profiles} predicate matches the
|
||||
* {@linkplain #getActiveProfiles() active profiles} — 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+12
-11
@@ -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
-2
@@ -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)
|
||||
*/
|
||||
|
||||
+2
-4
@@ -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} — for directories,
|
||||
* Delete the supplied {@link File} — 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
|
||||
|
||||
@@ -27,7 +27,6 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
@@ -927,15 +926,14 @@ public abstract class ObjectUtils {
|
||||
* <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>
|
||||
* if {@code obj} is a <em>simple 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:
|
||||
* a primitive wrapper (excluding {@code Void}), an {@code Enum}, a {@code Number},
|
||||
* a {@code Date}, a {@code Temporal}, a {@code UUID}, a {@code URI}, a {@code URL},
|
||||
* or a {@code Locale}.
|
||||
* <p>In the context of this method, a <em>simple type</em> is any of the following:
|
||||
* a primitive wrapper (excluding {@link Void}), an {@link Enum}, a {@link Number},
|
||||
* a {@link Date}, a {@link Temporal}, a {@link URI}, a {@link URL}, or a {@link Locale}.
|
||||
* @param obj the object to build a string representation for
|
||||
* @return a concise string representation of the supplied object
|
||||
* @since 5.3.27
|
||||
@@ -963,8 +961,13 @@ public abstract class ObjectUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Derived from {@link org.springframework.beans.BeanUtils#isSimpleValueType}.
|
||||
* As of 5.3.28, considering {@code UUID} in addition to the bean-level check.
|
||||
* Copy of {@link org.springframework.beans.BeanUtils#isSimpleValueType(Class)}.
|
||||
* <p>Check if the given type represents a "simple" value type: a primitive or
|
||||
* primitive wrapper, an enum, a String or other CharSequence, a Number, a
|
||||
* Date, a Temporal, a URI, a URL, a Locale, or a Class.
|
||||
* <p>{@code Void} and {@code void} are not considered simple value types.
|
||||
* @param type the type to check
|
||||
* @return whether the given type represents a "simple" value type
|
||||
*/
|
||||
private static boolean isSimpleValueType(Class<?> type) {
|
||||
return (Void.class != type && void.class != type &&
|
||||
@@ -974,7 +977,6 @@ public abstract class ObjectUtils {
|
||||
Number.class.isAssignableFrom(type) ||
|
||||
Date.class.isAssignableFrom(type) ||
|
||||
Temporal.class.isAssignableFrom(type) ||
|
||||
UUID.class == type ||
|
||||
URI.class == type ||
|
||||
URL.class == type ||
|
||||
Locale.class == type ||
|
||||
|
||||
@@ -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
|
||||
|
||||
+12
-12
@@ -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) {
|
||||
|
||||
+185
-339
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -827,17 +826,6 @@ class ObjectUtilsTests {
|
||||
.withMessage("Constant [bogus] does not exist in enum type org.springframework.util.ObjectUtilsTests$Tropes");
|
||||
}
|
||||
|
||||
|
||||
private static void assertEqualHashCodes(int expected, Object array) {
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
assertThat(array.hashCode()).isNotEqualTo(actual);
|
||||
}
|
||||
|
||||
|
||||
enum Tropes {FOO, BAR, baz}
|
||||
|
||||
|
||||
@Nested
|
||||
class NullSafeConciseToStringTests {
|
||||
|
||||
@@ -899,13 +887,7 @@ class ObjectUtilsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullSafeConciseToStringForUUID() {
|
||||
UUID id = UUID.randomUUID();
|
||||
assertThat(ObjectUtils.nullSafeConciseToString(id)).isEqualTo(id.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullSafeConciseToStringForURI() {
|
||||
void nullSafeConciseToStringForUri() {
|
||||
String uri = "https://www.example.com/?foo=1&bar=2&baz=3";
|
||||
assertThat(ObjectUtils.nullSafeConciseToString(URI.create(uri))).isEqualTo(uri);
|
||||
|
||||
@@ -917,7 +899,7 @@ class ObjectUtilsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullSafeConciseToStringForURL() throws Exception {
|
||||
void nullSafeConciseToStringForUrl() throws Exception {
|
||||
String url = "https://www.example.com/?foo=1&bar=2&baz=3";
|
||||
assertThat(ObjectUtils.nullSafeConciseToString(new URL(url))).isEqualTo(url);
|
||||
|
||||
@@ -977,6 +959,17 @@ class ObjectUtilsTests {
|
||||
private String prefix(Class<?> clazz) {
|
||||
return clazz.getTypeName() + "@";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static void assertEqualHashCodes(int expected, Object array) {
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
assertThat(array.hashCode() != actual).isTrue();
|
||||
}
|
||||
|
||||
|
||||
enum Tropes {FOO, BAR, baz}
|
||||
|
||||
}
|
||||
|
||||
+1
-5
@@ -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
-36
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+9
-3
@@ -93,6 +93,13 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
|
||||
private static final Pattern VALID_QUALIFIED_ID_PATTERN = Pattern.compile("[\\p{L}\\p{N}_$]+");
|
||||
|
||||
/**
|
||||
* Maximum length permitted for a SpEL expression.
|
||||
* @since 5.2.24
|
||||
*/
|
||||
private static final int MAX_EXPRESSION_LENGTH = 10_000;
|
||||
|
||||
|
||||
private final SpelParserConfiguration configuration;
|
||||
|
||||
// For rules that build nodes, they are stacked here for return
|
||||
@@ -151,9 +158,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
}
|
||||
|
||||
private void checkExpressionLength(String string) {
|
||||
int maxLength = this.configuration.getMaximumExpressionLength();
|
||||
if (string.length() > maxLength) {
|
||||
throw new SpelEvaluationException(SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED, maxLength);
|
||||
if (string.length() > MAX_EXPRESSION_LENGTH) {
|
||||
throw new SpelEvaluationException(SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED, MAX_EXPRESSION_LENGTH);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
* Copyright 2002-2014 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.util.Assert;
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class SpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
@@ -54,7 +53,6 @@ public class SpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
|
||||
|
||||
public SpelExpression parseRaw(String expressionString) throws ParseException {
|
||||
Assert.hasText(expressionString, "'expressionString' must not be null or blank");
|
||||
return doParseExpression(expressionString, null);
|
||||
}
|
||||
|
||||
|
||||
-18
@@ -164,24 +164,6 @@ public abstract class AbstractExpressionTests {
|
||||
*/
|
||||
protected void evaluateAndCheckError(String expression, Class<?> expectedReturnType, SpelMessage expectedMessage,
|
||||
Object... otherProperties) {
|
||||
|
||||
evaluateAndCheckError(this.parser, expression, expectedReturnType, expectedMessage, otherProperties);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate the specified expression and ensure the expected message comes out.
|
||||
* The message may have inserts and they will be checked if otherProperties is specified.
|
||||
* The first entry in otherProperties should always be the position.
|
||||
* @param parser the expression parser to use
|
||||
* @param expression the expression to evaluate
|
||||
* @param expectedReturnType ask the expression return value to be of this type if possible
|
||||
* ({@code null} indicates don't ask for conversion)
|
||||
* @param expectedMessage the expected message
|
||||
* @param otherProperties the expected inserts within the message
|
||||
*/
|
||||
protected void evaluateAndCheckError(ExpressionParser parser, String expression, Class<?> expectedReturnType, SpelMessage expectedMessage,
|
||||
Object... otherProperties) {
|
||||
|
||||
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> {
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
assertThat(expr).as("expression").isNotNull();
|
||||
|
||||
-20
@@ -77,26 +77,6 @@ class EvaluationTests extends AbstractExpressionTests {
|
||||
evaluateAndCheckError(expression, String.class, SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxExpressionLengthIsConfigurable() {
|
||||
int maximumExpressionLength = 20_000;
|
||||
|
||||
String expression = String.format("'%s'", repeat("Y", 19_998));
|
||||
assertThat(expression).hasSize(maximumExpressionLength);
|
||||
|
||||
SpelParserConfiguration configuration =
|
||||
new SpelParserConfiguration(null, null, false, false, 0, maximumExpressionLength);
|
||||
ExpressionParser parser = new SpelExpressionParser(configuration);
|
||||
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
String result = expr.getValue(String.class);
|
||||
assertThat(result).hasSize(19_998);
|
||||
|
||||
expression = String.format("'%s'", repeat("Y", 25_000));
|
||||
assertThat(expression).hasSize(25_002);
|
||||
evaluateAndCheckError(parser, expression, String.class, SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createListsOnAttemptToIndexNull01() throws EvaluationException, ParseException {
|
||||
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
|
||||
|
||||
+21
-26
@@ -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.
|
||||
@@ -30,16 +30,14 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
|
||||
/**
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
public class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
|
||||
static final ParserContext DEFAULT_TEMPLATE_PARSER_CONTEXT = new ParserContext() {
|
||||
public static final ParserContext DEFAULT_TEMPLATE_PARSER_CONTEXT = new ParserContext() {
|
||||
@Override
|
||||
public String getExpressionPrefix() {
|
||||
return "${";
|
||||
@@ -54,7 +52,7 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
}
|
||||
};
|
||||
|
||||
static final ParserContext HASH_DELIMITED_PARSER_CONTEXT = new ParserContext() {
|
||||
public static final ParserContext HASH_DELIMITED_PARSER_CONTEXT = new ParserContext() {
|
||||
@Override
|
||||
public String getExpressionPrefix() {
|
||||
return "#{";
|
||||
@@ -70,32 +68,25 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
};
|
||||
|
||||
|
||||
private final SpelExpressionParser parser = new SpelExpressionParser();
|
||||
|
||||
|
||||
@Test
|
||||
void nullTemplateExpressionIsRejected() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> parser.parseExpression(null, DEFAULT_TEMPLATE_PARSER_CONTEXT))
|
||||
.withMessage("'expressionString' must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsingSimpleTemplateExpression01() {
|
||||
public void testParsingSimpleTemplateExpression01() throws Exception {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
Expression expr = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
Object o = expr.getValue();
|
||||
assertThat(o.toString()).isEqualTo("hello world");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsingSimpleTemplateExpression02() {
|
||||
public void testParsingSimpleTemplateExpression02() throws Exception {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
Expression expr = parser.parseExpression("hello ${'to'} you", DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
Object o = expr.getValue();
|
||||
assertThat(o.toString()).isEqualTo("hello to you");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsingSimpleTemplateExpression03() {
|
||||
public void testParsingSimpleTemplateExpression03() throws Exception {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
Expression expr = parser.parseExpression("The quick ${'brown'} fox jumped over the ${'lazy'} dog",
|
||||
DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
Object o = expr.getValue();
|
||||
@@ -103,7 +94,8 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsingSimpleTemplateExpression04() {
|
||||
public void testParsingSimpleTemplateExpression04() throws Exception {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
Expression expr = parser.parseExpression("${'hello'} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
Object o = expr.getValue();
|
||||
assertThat(o.toString()).isEqualTo("hello world");
|
||||
@@ -122,7 +114,8 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void compositeStringExpression() {
|
||||
public void testCompositeStringExpression() throws Exception {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
Expression ex = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
assertThat(ex.getValue()).isInstanceOf(String.class).isEqualTo("hello world");
|
||||
assertThat(ex.getValue(String.class)).isInstanceOf(String.class).isEqualTo("hello world");
|
||||
@@ -161,7 +154,8 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
static class Rooty {}
|
||||
|
||||
@Test
|
||||
void nestedExpressions() {
|
||||
public void testNestedExpressions() throws Exception {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
// treat the nested ${..} as a part of the expression
|
||||
Expression ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
|
||||
@@ -191,7 +185,8 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void clashingWithSuffixes() {
|
||||
|
||||
public void testClashingWithSuffixes() throws Exception {
|
||||
// Just wanting to use the prefix or suffix within the template:
|
||||
Expression ex = parser.parseExpression("hello ${3+4} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
|
||||
String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
|
||||
@@ -207,13 +202,13 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsingNormalExpressionThroughTemplateParser() {
|
||||
public void testParsingNormalExpressionThroughTemplateParser() throws Exception {
|
||||
Expression expr = parser.parseExpression("1+2+3");
|
||||
assertThat(expr.getValue()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorCases() {
|
||||
public void testErrorCases() throws Exception {
|
||||
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
|
||||
parser.parseExpression("hello ${'world'", DEFAULT_TEMPLATE_PARSER_CONTEXT))
|
||||
.satisfies(pex -> {
|
||||
@@ -229,7 +224,7 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTemplateParserContext() {
|
||||
public void testTemplateParserContext() {
|
||||
TemplateParserContext tpc = new TemplateParserContext("abc","def");
|
||||
assertThat(tpc.getExpressionPrefix()).isEqualTo("abc");
|
||||
assertThat(tpc.getExpressionSuffix()).isEqualTo("def");
|
||||
|
||||
+103
-113
@@ -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.
|
||||
@@ -18,8 +18,6 @@ package org.springframework.expression.spel.standard;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
|
||||
import org.assertj.core.api.ThrowableAssertAlternative;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
@@ -33,55 +31,16 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
|
||||
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.expression.spel.SpelMessage.MISSING_CONSTRUCTOR_ARGS;
|
||||
import static org.springframework.expression.spel.SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING;
|
||||
import static org.springframework.expression.spel.SpelMessage.NON_TERMINATING_QUOTED_STRING;
|
||||
import static org.springframework.expression.spel.SpelMessage.NOT_AN_INTEGER;
|
||||
import static org.springframework.expression.spel.SpelMessage.NOT_A_LONG;
|
||||
import static org.springframework.expression.spel.SpelMessage.REAL_CANNOT_BE_LONG;
|
||||
import static org.springframework.expression.spel.SpelMessage.RUN_OUT_OF_ARGUMENTS;
|
||||
import static org.springframework.expression.spel.SpelMessage.UNEXPECTED_DATA_AFTER_DOT;
|
||||
import static org.springframework.expression.spel.SpelMessage.UNEXPECTED_ESCAPE_CHAR;
|
||||
|
||||
/**
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
class SpelParserTests {
|
||||
|
||||
private final SpelExpressionParser parser = new SpelExpressionParser();
|
||||
|
||||
|
||||
@Test
|
||||
void nullExpressionIsRejected() {
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseExpression(null));
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseRaw(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyExpressionIsRejected() {
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseExpression(""));
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseRaw(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankExpressionIsRejected() {
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseExpression(" "));
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseExpression("\t\n"));
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseRaw(" "));
|
||||
assertNullOrEmptyExpressionIsRejected(() -> parser.parseRaw("\t\n"));
|
||||
}
|
||||
|
||||
private static void assertNullOrEmptyExpressionIsRejected(ThrowingCallable throwingCallable) {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessage("'expressionString' must not be null or blank");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMostBasic() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("2");
|
||||
assertThat(expr).isNotNull();
|
||||
assertThat(expr.getAST()).isNotNull();
|
||||
@@ -92,6 +51,7 @@ class SpelParserTests {
|
||||
|
||||
@Test
|
||||
void valueType() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
EvaluationContext ctx = new StandardEvaluationContext();
|
||||
Class<?> c = parser.parseRaw("2").getValueType();
|
||||
assertThat(c).isEqualTo(Integer.class);
|
||||
@@ -107,6 +67,7 @@ class SpelParserTests {
|
||||
|
||||
@Test
|
||||
void whitespace() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("2 + 3");
|
||||
assertThat(expr.getValue()).isEqualTo(5);
|
||||
expr = parser.parseRaw("2 + 3");
|
||||
@@ -119,6 +80,7 @@ class SpelParserTests {
|
||||
|
||||
@Test
|
||||
void arithmeticPlus1() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("2+2");
|
||||
assertThat(expr).isNotNull();
|
||||
assertThat(expr.getAST()).isNotNull();
|
||||
@@ -127,12 +89,14 @@ class SpelParserTests {
|
||||
|
||||
@Test
|
||||
void arithmeticPlus2() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("37+41");
|
||||
assertThat(expr.getValue()).isEqualTo(78);
|
||||
}
|
||||
|
||||
@Test
|
||||
void arithmeticMultiply1() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("2*3");
|
||||
assertThat(expr).isNotNull();
|
||||
assertThat(expr.getAST()).isNotNull();
|
||||
@@ -141,120 +105,162 @@ class SpelParserTests {
|
||||
|
||||
@Test
|
||||
void arithmeticPrecedence1() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("2*3+5");
|
||||
assertThat(expr.getValue()).isEqualTo(11);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseExceptions() {
|
||||
assertParseException(() -> parser.parseRaw("new String"), MISSING_CONSTRUCTOR_ARGS, 10);
|
||||
assertParseException(() -> parser.parseRaw("new String(3,"), RUN_OUT_OF_ARGUMENTS, 10);
|
||||
assertParseException(() -> parser.parseRaw("new String(3"), RUN_OUT_OF_ARGUMENTS, 10);
|
||||
assertParseException(() -> parser.parseRaw("new String("), RUN_OUT_OF_ARGUMENTS, 10);
|
||||
assertParseException(() -> parser.parseRaw("\"abc"), NON_TERMINATING_DOUBLE_QUOTED_STRING, 0);
|
||||
assertParseException(() -> parser.parseRaw("'abc"), NON_TERMINATING_QUOTED_STRING, 0);
|
||||
void generalExpressions() {
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
parser.parseRaw("new String");
|
||||
})
|
||||
.satisfies(parseExceptionRequirements(SpelMessage.MISSING_CONSTRUCTOR_ARGS, 10));
|
||||
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
parser.parseRaw("new String(3,");
|
||||
})
|
||||
.satisfies(parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10));
|
||||
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
parser.parseRaw("new String(3");
|
||||
})
|
||||
.satisfies(parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10));
|
||||
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
parser.parseRaw("new String(");
|
||||
})
|
||||
.satisfies(parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10));
|
||||
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
parser.parseRaw("\"abc");
|
||||
})
|
||||
.satisfies(parseExceptionRequirements(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 0));
|
||||
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
parser.parseRaw("'abc");
|
||||
})
|
||||
.satisfies(parseExceptionRequirements(SpelMessage.NON_TERMINATING_QUOTED_STRING, 0));
|
||||
|
||||
}
|
||||
|
||||
private <E extends SpelParseException> Consumer<E> parseExceptionRequirements(
|
||||
SpelMessage expectedMessage, int expectedPosition) {
|
||||
return ex -> {
|
||||
assertThat(ex.getMessageCode()).isEqualTo(expectedMessage);
|
||||
assertThat(ex.getPosition()).isEqualTo(expectedPosition);
|
||||
assertThat(ex.getMessage()).contains(ex.getExpressionString());
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void arithmeticPrecedence2() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw("2+3*5");
|
||||
assertThat(expr.getValue()).isEqualTo(17);
|
||||
}
|
||||
|
||||
@Test
|
||||
void arithmeticPrecedence3() {
|
||||
SpelExpression expr = parser.parseRaw("3+10/2");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("3+10/2");
|
||||
assertThat(expr.getValue()).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void arithmeticPrecedence4() {
|
||||
SpelExpression expr = parser.parseRaw("10/2+3");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("10/2+3");
|
||||
assertThat(expr.getValue()).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void arithmeticPrecedence5() {
|
||||
SpelExpression expr = parser.parseRaw("(4+10)/2");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("(4+10)/2");
|
||||
assertThat(expr.getValue()).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void arithmeticPrecedence6() {
|
||||
SpelExpression expr = parser.parseRaw("(3+2)*2");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("(3+2)*2");
|
||||
assertThat(expr.getValue()).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
void booleanOperators() {
|
||||
SpelExpression expr = parser.parseRaw("true");
|
||||
assertThat(expr.getValue(Boolean.class)).isTrue();
|
||||
expr = parser.parseRaw("false");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
expr = parser.parseRaw("false and false");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
expr = parser.parseRaw("true and (true or false)");
|
||||
assertThat(expr.getValue(Boolean.class)).isTrue();
|
||||
expr = parser.parseRaw("true and true or false");
|
||||
assertThat(expr.getValue(Boolean.class)).isTrue();
|
||||
expr = parser.parseRaw("!true");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
expr = parser.parseRaw("!(false or true)");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("true");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||
expr = new SpelExpressionParser().parseRaw("false");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
expr = new SpelExpressionParser().parseRaw("false and false");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
expr = new SpelExpressionParser().parseRaw("true and (true or false)");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||
expr = new SpelExpressionParser().parseRaw("true and true or false");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||
expr = new SpelExpressionParser().parseRaw("!true");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
expr = new SpelExpressionParser().parseRaw("!(false or true)");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void booleanOperators_symbolic_spr9614() {
|
||||
SpelExpression expr = parser.parseRaw("true");
|
||||
assertThat(expr.getValue(Boolean.class)).isTrue();
|
||||
expr = parser.parseRaw("false");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
expr = parser.parseRaw("false && false");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
expr = parser.parseRaw("true && (true || false)");
|
||||
assertThat(expr.getValue(Boolean.class)).isTrue();
|
||||
expr = parser.parseRaw("true && true || false");
|
||||
assertThat(expr.getValue(Boolean.class)).isTrue();
|
||||
expr = parser.parseRaw("!true");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
expr = parser.parseRaw("!(false || true)");
|
||||
assertThat(expr.getValue(Boolean.class)).isFalse();
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("true");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||
expr = new SpelExpressionParser().parseRaw("false");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
expr = new SpelExpressionParser().parseRaw("false && false");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
expr = new SpelExpressionParser().parseRaw("true && (true || false)");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||
expr = new SpelExpressionParser().parseRaw("true && true || false");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE);
|
||||
expr = new SpelExpressionParser().parseRaw("!true");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
expr = new SpelExpressionParser().parseRaw("!(false || true)");
|
||||
assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringLiterals() {
|
||||
SpelExpression expr = parser.parseRaw("'howdy'");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("'howdy'");
|
||||
assertThat(expr.getValue()).isEqualTo("howdy");
|
||||
expr = parser.parseRaw("'hello '' world'");
|
||||
expr = new SpelExpressionParser().parseRaw("'hello '' world'");
|
||||
assertThat(expr.getValue()).isEqualTo("hello ' world");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringLiterals2() {
|
||||
SpelExpression expr = parser.parseRaw("'howdy'.substring(0,2)");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("'howdy'.substring(0,2)");
|
||||
assertThat(expr.getValue()).isEqualTo("ho");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStringLiterals_DoubleQuotes_spr9620() {
|
||||
SpelExpression expr = parser.parseRaw("\"double quote: \"\".\"");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("\"double quote: \"\".\"");
|
||||
assertThat(expr.getValue()).isEqualTo("double quote: \".");
|
||||
expr = parser.parseRaw("\"hello \"\" world\"");
|
||||
expr = new SpelExpressionParser().parseRaw("\"hello \"\" world\"");
|
||||
assertThat(expr.getValue()).isEqualTo("hello \" world");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStringLiterals_DoubleQuotes_spr9620_2() {
|
||||
assertParseExceptionThrownBy(() -> parser.parseRaw("\"double quote: \\\"\\\".\""))
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
|
||||
new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\""))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getPosition()).isEqualTo(17);
|
||||
assertThat(ex.getMessageCode()).isEqualTo(UNEXPECTED_ESCAPE_CHAR);
|
||||
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.UNEXPECTED_ESCAPE_CHAR);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void positionalInformation() {
|
||||
SpelExpression expr = parser.parseRaw("true and true or false");
|
||||
SpelExpression expr = new SpelExpressionParser().parseRaw("true and true or false");
|
||||
SpelNode rootAst = expr.getAST();
|
||||
OpOr operatorOr = (OpOr) rootAst;
|
||||
OpAnd operatorAnd = (OpAnd) operatorOr.getLeftOperand();
|
||||
@@ -349,10 +355,10 @@ class SpelParserTests {
|
||||
checkNumber("0xa", 10, Integer.class);
|
||||
checkNumber("0xAL", 10L, Long.class);
|
||||
|
||||
checkNumberError("0x", NOT_AN_INTEGER);
|
||||
checkNumberError("0xL", NOT_A_LONG);
|
||||
checkNumberError(".324", UNEXPECTED_DATA_AFTER_DOT);
|
||||
checkNumberError("3.4L", REAL_CANNOT_BE_LONG);
|
||||
checkNumberError("0x", SpelMessage.NOT_AN_INTEGER);
|
||||
checkNumberError("0xL", SpelMessage.NOT_A_LONG);
|
||||
checkNumberError(".324", SpelMessage.UNEXPECTED_DATA_AFTER_DOT);
|
||||
checkNumberError("3.4L", SpelMessage.REAL_CANNOT_BE_LONG);
|
||||
|
||||
checkNumber("3.5f", 3.5f, Float.class);
|
||||
checkNumber("1.2e3", 1.2e3d, Double.class);
|
||||
@@ -365,6 +371,7 @@ class SpelParserTests {
|
||||
|
||||
private void checkNumber(String expression, Object value, Class<?> type) {
|
||||
try {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
SpelExpression expr = parser.parseRaw(expression);
|
||||
Object exprVal = expr.getValue();
|
||||
assertThat(exprVal).isEqualTo(value);
|
||||
@@ -376,26 +383,9 @@ class SpelParserTests {
|
||||
}
|
||||
|
||||
private void checkNumberError(String expression, SpelMessage expectedMessage) {
|
||||
assertParseExceptionThrownBy(() -> parser.parseRaw(expression))
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> parser.parseRaw(expression))
|
||||
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(expectedMessage));
|
||||
}
|
||||
|
||||
private static ThrowableAssertAlternative<SpelParseException> assertParseExceptionThrownBy(ThrowingCallable throwingCallable) {
|
||||
return assertThatExceptionOfType(SpelParseException.class).isThrownBy(throwingCallable);
|
||||
}
|
||||
|
||||
private static void assertParseException(ThrowingCallable throwingCallable, SpelMessage expectedMessage, int expectedPosition) {
|
||||
assertParseExceptionThrownBy(throwingCallable)
|
||||
.satisfies(parseExceptionRequirements(expectedMessage, expectedPosition));
|
||||
}
|
||||
|
||||
private static <E extends SpelParseException> Consumer<E> parseExceptionRequirements(
|
||||
SpelMessage expectedMessage, int expectedPosition) {
|
||||
return ex -> {
|
||||
assertThat(ex.getMessageCode()).isEqualTo(expectedMessage);
|
||||
assertThat(ex.getPosition()).isEqualTo(expectedPosition);
|
||||
assertThat(ex.getMessage()).contains(ex.getExpressionString());
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+53
-57
@@ -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.
|
||||
@@ -35,52 +35,49 @@ import org.springframework.transaction.support.TransactionSynchronizationUtils;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* {@link org.springframework.transaction.PlatformTransactionManager} implementation
|
||||
* for a single JDBC {@link javax.sql.DataSource}. This class is capable of working
|
||||
* in any environment with any JDBC driver, as long as the setup uses a
|
||||
* {@code javax.sql.DataSource} as its {@code Connection} factory mechanism.
|
||||
* Binds a JDBC {@code Connection} from the specified {@code DataSource} to the
|
||||
* current thread, potentially allowing for one thread-bound {@code Connection}
|
||||
* per {@code DataSource}.
|
||||
* {@link org.springframework.transaction.PlatformTransactionManager}
|
||||
* implementation for a single JDBC {@link javax.sql.DataSource}. This class is
|
||||
* capable of working in any environment with any JDBC driver, as long as the setup
|
||||
* uses a {@code javax.sql.DataSource} as its {@code Connection} factory mechanism.
|
||||
* Binds a JDBC Connection from the specified DataSource to the current thread,
|
||||
* potentially allowing for one thread-bound Connection per DataSource.
|
||||
*
|
||||
* <p><b>Note: The {@code DataSource} that this transaction manager operates on
|
||||
* needs to return independent {@code Connection}s.</b> The {@code Connection}s
|
||||
* typically come from a connection pool but the {@code DataSource} must not return
|
||||
* specifically scoped or constrained {@code Connection}s. This transaction manager
|
||||
* will associate {@code Connection}s with thread-bound transactions, according
|
||||
* to the specified propagation behavior. It assumes that a separate, independent
|
||||
* {@code Connection} can be obtained even during an ongoing transaction.
|
||||
* <p><b>Note: The DataSource that this transaction manager operates on needs
|
||||
* to return independent Connections.</b> The Connections may come from a pool
|
||||
* (the typical case), but the DataSource must not return thread-scoped /
|
||||
* request-scoped Connections or the like. This transaction manager will
|
||||
* associate Connections with thread-bound transactions itself, according
|
||||
* to the specified propagation behavior. It assumes that a separate,
|
||||
* independent Connection can be obtained even during an ongoing transaction.
|
||||
*
|
||||
* <p>Application code is required to retrieve the JDBC {@code Connection} via
|
||||
* <p>Application code is required to retrieve the JDBC Connection via
|
||||
* {@link DataSourceUtils#getConnection(DataSource)} instead of a standard
|
||||
* EE-style {@link DataSource#getConnection()} call. Spring classes such as
|
||||
* Java EE-style {@link DataSource#getConnection()} call. Spring classes such as
|
||||
* {@link org.springframework.jdbc.core.JdbcTemplate} use this strategy implicitly.
|
||||
* If not used in combination with this transaction manager, the
|
||||
* {@link DataSourceUtils} lookup strategy behaves exactly like the native
|
||||
* {@code DataSource} lookup; it can thus be used in a portable fashion.
|
||||
* DataSource lookup; it can thus be used in a portable fashion.
|
||||
*
|
||||
* <p>Alternatively, you can allow application code to work with the standard
|
||||
* EE-style lookup pattern {@link DataSource#getConnection()}, for example
|
||||
* for legacy code that is not aware of Spring at all. In that case, define a
|
||||
* {@link TransactionAwareDataSourceProxy} for your target {@code DataSource},
|
||||
* and pass that proxy {@code DataSource} to your DAOs which will automatically
|
||||
* participate in Spring-managed transactions when accessing it.
|
||||
* Java EE-style lookup pattern {@link DataSource#getConnection()}, for example for
|
||||
* legacy code that is not aware of Spring at all. In that case, define a
|
||||
* {@link TransactionAwareDataSourceProxy} for your target DataSource, and pass
|
||||
* that proxy DataSource to your DAOs, which will automatically participate in
|
||||
* Spring-managed transactions when accessing it.
|
||||
*
|
||||
* <p>Supports custom isolation levels, and timeouts which get applied as
|
||||
* appropriate JDBC statement timeouts. To support the latter, application code
|
||||
* must either use {@link org.springframework.jdbc.core.JdbcTemplate}, call
|
||||
* {@link DataSourceUtils#applyTransactionTimeout} for each created JDBC
|
||||
* {@code Statement}, or go through a {@link TransactionAwareDataSourceProxy}
|
||||
* which will create timeout-aware JDBC {@code Connection}s and {@code Statement}s
|
||||
* automatically.
|
||||
* {@link DataSourceUtils#applyTransactionTimeout} for each created JDBC Statement,
|
||||
* or go through a {@link TransactionAwareDataSourceProxy} which will create
|
||||
* timeout-aware JDBC Connections and Statements automatically.
|
||||
*
|
||||
* <p>Consider defining a {@link LazyConnectionDataSourceProxy} for your target
|
||||
* {@code DataSource}, pointing both this transaction manager and your DAOs to it.
|
||||
* DataSource, pointing both this transaction manager and your DAOs to it.
|
||||
* This will lead to optimized handling of "empty" transactions, i.e. of transactions
|
||||
* without any JDBC statements executed. A {@code LazyConnectionDataSourceProxy} will
|
||||
* not fetch an actual JDBC {@code Connection} from the target {@code DataSource}
|
||||
* until a {@code Statement} gets executed, lazily applying the specified transaction
|
||||
* settings to the target {@code Connection}.
|
||||
* without any JDBC statements executed. A LazyConnectionDataSourceProxy will not fetch
|
||||
* an actual JDBC Connection from the target DataSource until a Statement gets executed,
|
||||
* lazily applying the specified transaction settings to the target Connection.
|
||||
*
|
||||
* <p>This transaction manager supports nested transactions via the JDBC 3.0
|
||||
* {@link java.sql.Savepoint} mechanism. The
|
||||
@@ -91,9 +88,9 @@ import org.springframework.util.Assert;
|
||||
* <p>This transaction manager can be used as a replacement for the
|
||||
* {@link org.springframework.transaction.jta.JtaTransactionManager} in the single
|
||||
* resource case, as it does not require a container that supports JTA, typically
|
||||
* in combination with a locally defined JDBC {@code DataSource} (e.g. a Hikari
|
||||
* connection pool). Switching between this local strategy and a JTA environment
|
||||
* is just a matter of configuration!
|
||||
* in combination with a locally defined JDBC DataSource (e.g. an Apache Commons
|
||||
* DBCP connection pool). Switching between this local strategy and a JTA
|
||||
* environment is just a matter of configuration!
|
||||
*
|
||||
* <p>As of 4.3.4, this transaction manager triggers flush callbacks on registered
|
||||
* transaction synchronizations (if synchronization is generally active), assuming
|
||||
@@ -115,7 +112,6 @@ import org.springframework.util.Assert;
|
||||
* @see TransactionAwareDataSourceProxy
|
||||
* @see LazyConnectionDataSourceProxy
|
||||
* @see org.springframework.jdbc.core.JdbcTemplate
|
||||
* @see org.springframework.jdbc.support.JdbcTransactionManager
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager
|
||||
@@ -128,8 +124,8 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@code DataSourceTransactionManager} instance.
|
||||
* A {@code DataSource} has to be set to be able to use it.
|
||||
* Create a new DataSourceTransactionManager instance.
|
||||
* A DataSource has to be set to be able to use it.
|
||||
* @see #setDataSource
|
||||
*/
|
||||
public DataSourceTransactionManager() {
|
||||
@@ -137,7 +133,7 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@code DataSourceTransactionManager} instance.
|
||||
* Create a new DataSourceTransactionManager instance.
|
||||
* @param dataSource the JDBC DataSource to manage transactions for
|
||||
*/
|
||||
public DataSourceTransactionManager(DataSource dataSource) {
|
||||
@@ -148,22 +144,22 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
|
||||
|
||||
|
||||
/**
|
||||
* Set the JDBC {@code DataSource} that this instance should manage transactions for.
|
||||
* <p>This will typically be a locally defined {@code DataSource}, for example a
|
||||
* Hikari connection pool. Alternatively, you can also manage transactions for a
|
||||
* non-XA {@code DataSource} fetched from JNDI. For an XA {@code DataSource},
|
||||
* use {@link org.springframework.transaction.jta.JtaTransactionManager} instead.
|
||||
* <p>The {@code DataSource} specified here should be the target {@code DataSource}
|
||||
* to manage transactions for, not a {@link TransactionAwareDataSourceProxy}.
|
||||
* Only data access code may work with {@code TransactionAwareDataSourceProxy} while
|
||||
* the transaction manager needs to work on the underlying target {@code DataSource}.
|
||||
* If there is nevertheless a {@code TransactionAwareDataSourceProxy} passed in,
|
||||
* it will be unwrapped to extract its target {@code DataSource}.
|
||||
* <p><b>The {@code DataSource} passed in here needs to return independent
|
||||
* {@code Connection}s.</b> The {@code Connection}s typically come from a
|
||||
* connection pool but the {@code DataSource} must not return specifically
|
||||
* scoped or constrained {@code Connection}s, just possibly lazily fetched.
|
||||
* @see LazyConnectionDataSourceProxy
|
||||
* Set the JDBC DataSource that this instance should manage transactions for.
|
||||
* <p>This will typically be a locally defined DataSource, for example an
|
||||
* Apache Commons DBCP connection pool. Alternatively, you can also drive
|
||||
* transactions for a non-XA J2EE DataSource fetched from JNDI. For an XA
|
||||
* DataSource, use JtaTransactionManager.
|
||||
* <p>The DataSource specified here should be the target DataSource to manage
|
||||
* transactions for, not a TransactionAwareDataSourceProxy. Only data access
|
||||
* code may work with TransactionAwareDataSourceProxy, while the transaction
|
||||
* manager needs to work on the underlying target DataSource. If there's
|
||||
* nevertheless a TransactionAwareDataSourceProxy passed in, it will be
|
||||
* unwrapped to extract its target DataSource.
|
||||
* <p><b>The DataSource passed in here needs to return independent Connections.</b>
|
||||
* The Connections may come from a pool (the typical case), but the DataSource
|
||||
* must not return thread-scoped / request-scoped Connections or the like.
|
||||
* @see TransactionAwareDataSourceProxy
|
||||
* @see org.springframework.transaction.jta.JtaTransactionManager
|
||||
*/
|
||||
public void setDataSource(@Nullable DataSource dataSource) {
|
||||
if (dataSource instanceof TransactionAwareDataSourceProxy) {
|
||||
@@ -178,7 +174,7 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the JDBC {@code DataSource} that this instance manages transactions for.
|
||||
* Return the JDBC DataSource that this instance manages transactions for.
|
||||
*/
|
||||
@Nullable
|
||||
public DataSource getDataSource() {
|
||||
@@ -186,7 +182,7 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the {@code DataSource} for actual use.
|
||||
* Obtain the DataSource for actual use.
|
||||
* @return the DataSource (never {@code null})
|
||||
* @throws IllegalStateException in case of no DataSource set
|
||||
* @since 5.0
|
||||
|
||||
@@ -33,9 +33,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Helper class that provides static methods for obtaining JDBC {@code Connection}s
|
||||
* from a {@link javax.sql.DataSource}. Includes special support for Spring-managed
|
||||
* transactional {@code Connection}s, e.g. managed by {@link DataSourceTransactionManager}
|
||||
* Helper class that provides static methods for obtaining JDBC Connections from
|
||||
* a {@link javax.sql.DataSource}. Includes special support for Spring-managed
|
||||
* transactional Connections, e.g. managed by {@link DataSourceTransactionManager}
|
||||
* or {@link org.springframework.transaction.jta.JtaTransactionManager}.
|
||||
*
|
||||
* <p>Used internally by Spring's {@link org.springframework.jdbc.core.JdbcTemplate},
|
||||
@@ -46,8 +46,7 @@ import org.springframework.util.Assert;
|
||||
* @author Juergen Hoeller
|
||||
* @see #getConnection
|
||||
* @see #releaseConnection
|
||||
* @see org.springframework.jdbc.core.JdbcTemplate
|
||||
* @see org.springframework.jdbc.support.JdbcTransactionManager
|
||||
* @see DataSourceTransactionManager
|
||||
* @see org.springframework.transaction.jta.JtaTransactionManager
|
||||
* @see org.springframework.transaction.support.TransactionSynchronizationManager
|
||||
*/
|
||||
@@ -475,7 +474,7 @@ public abstract class DataSourceUtils {
|
||||
|
||||
private final DataSource dataSource;
|
||||
|
||||
private final int order;
|
||||
private int order;
|
||||
|
||||
private boolean holderActive = true;
|
||||
|
||||
|
||||
+12
-12
@@ -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.
|
||||
@@ -27,8 +27,8 @@ import org.springframework.util.backoff.BackOff;
|
||||
* A {@link JmsListenerContainerFactory} implementation to build a regular
|
||||
* {@link DefaultMessageListenerContainer}.
|
||||
*
|
||||
* <p>This should be the default for most users and a good transition path
|
||||
* for those who are used to building such a container definition manually.
|
||||
* <p>This should be the default for most users and a good transition paths
|
||||
* for those that are used to build such container definition manually.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @since 4.1
|
||||
@@ -67,63 +67,63 @@ public class DefaultJmsListenerContainerFactory
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setTaskExecutor
|
||||
*/
|
||||
public void setTaskExecutor(@Nullable Executor taskExecutor) {
|
||||
public void setTaskExecutor(Executor taskExecutor) {
|
||||
this.taskExecutor = taskExecutor;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setTransactionManager
|
||||
*/
|
||||
public void setTransactionManager(@Nullable PlatformTransactionManager transactionManager) {
|
||||
public void setTransactionManager(PlatformTransactionManager transactionManager) {
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setCacheLevel
|
||||
*/
|
||||
public void setCacheLevel(@Nullable Integer cacheLevel) {
|
||||
public void setCacheLevel(Integer cacheLevel) {
|
||||
this.cacheLevel = cacheLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setCacheLevelName
|
||||
*/
|
||||
public void setCacheLevelName(@Nullable String cacheLevelName) {
|
||||
public void setCacheLevelName(String cacheLevelName) {
|
||||
this.cacheLevelName = cacheLevelName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setConcurrency
|
||||
*/
|
||||
public void setConcurrency(@Nullable String concurrency) {
|
||||
public void setConcurrency(String concurrency) {
|
||||
this.concurrency = concurrency;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setMaxMessagesPerTask
|
||||
*/
|
||||
public void setMaxMessagesPerTask(@Nullable Integer maxMessagesPerTask) {
|
||||
public void setMaxMessagesPerTask(Integer maxMessagesPerTask) {
|
||||
this.maxMessagesPerTask = maxMessagesPerTask;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setReceiveTimeout
|
||||
*/
|
||||
public void setReceiveTimeout(@Nullable Long receiveTimeout) {
|
||||
public void setReceiveTimeout(Long receiveTimeout) {
|
||||
this.receiveTimeout = receiveTimeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setRecoveryInterval
|
||||
*/
|
||||
public void setRecoveryInterval(@Nullable Long recoveryInterval) {
|
||||
public void setRecoveryInterval(Long recoveryInterval) {
|
||||
this.recoveryInterval = recoveryInterval;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DefaultMessageListenerContainer#setBackOff
|
||||
*/
|
||||
public void setBackOff(@Nullable BackOff backOff) {
|
||||
public void setBackOff(BackOff backOff) {
|
||||
this.backOff = backOff;
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -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.
|
||||
@@ -105,7 +105,7 @@ import org.springframework.util.Assert;
|
||||
* @see DataSourceUtils#getConnection
|
||||
* @see DataSourceUtils#releaseConnection
|
||||
* @see org.springframework.jdbc.core.JdbcTemplate
|
||||
* @see org.springframework.jdbc.support.JdbcTransactionManager
|
||||
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
|
||||
* @see org.springframework.transaction.jta.JtaTransactionManager
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
|
||||
@@ -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.
|
||||
@@ -109,7 +109,7 @@ import org.springframework.util.CollectionUtils;
|
||||
* @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection
|
||||
* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
|
||||
* @see org.springframework.jdbc.core.JdbcTemplate
|
||||
* @see org.springframework.jdbc.support.JdbcTransactionManager
|
||||
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
|
||||
* @see org.springframework.transaction.jta.JtaTransactionManager
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
|
||||
+14
-40
@@ -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.
|
||||
@@ -22,7 +22,6 @@ import java.sql.SQLException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import org.eclipse.persistence.sessions.DatabaseLogin;
|
||||
import org.eclipse.persistence.sessions.UnitOfWork;
|
||||
|
||||
import org.springframework.jdbc.datasource.ConnectionHandle;
|
||||
@@ -36,20 +35,14 @@ import org.springframework.transaction.TransactionException;
|
||||
* Persistence Services (EclipseLink). Developed and tested against EclipseLink 2.7;
|
||||
* backwards-compatible with EclipseLink 2.5 and 2.6 at runtime.
|
||||
*
|
||||
* <p>By default, this dialect acquires an early EclipseLink transaction with an
|
||||
* early JDBC Connection for non-read-only transactions. This allows for mixing
|
||||
* JDBC and JPA operations in the same transaction, with cross visibility of
|
||||
* <p>By default, this class acquires an early EclipseLink transaction with an early
|
||||
* JDBC Connection for non-read-only transactions. This allows for mixing JDBC and
|
||||
* JPA/EclipseLink operations in the same transaction, with cross visibility of
|
||||
* their impact. If this is not needed, set the "lazyDatabaseTransaction" flag to
|
||||
* {@code true} or consistently declare all affected transactions as read-only.
|
||||
* As of Spring 4.1.2, this will reliably avoid early JDBC Connection retrieval
|
||||
* and therefore keep EclipseLink in shared cache mode.
|
||||
*
|
||||
* <p><b>NOTE: This dialect supports custom isolation levels with limitations.</b>
|
||||
* Consistent isolation level handling is only guaranteed when all Spring transaction
|
||||
* definitions specify a concrete isolation level, without any default transactions
|
||||
* running concurrently. Otherwise, you may see non-default isolation levels exposed
|
||||
* to default transactions when custom isolation is used in concurrent transactions.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.5.2
|
||||
* @see #setLazyDatabaseTransaction
|
||||
@@ -85,38 +78,19 @@ public class EclipseLinkJpaDialect extends DefaultJpaDialect {
|
||||
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
|
||||
throws PersistenceException, SQLException, TransactionException {
|
||||
|
||||
int currentIsolationLevel = definition.getIsolationLevel();
|
||||
if (currentIsolationLevel != TransactionDefinition.ISOLATION_DEFAULT) {
|
||||
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
|
||||
// Pass custom isolation level on to EclipseLink's DatabaseLogin configuration
|
||||
// (since Spring 4.1.2 / revised in 5.3.28)
|
||||
// (since Spring 4.1.2)
|
||||
UnitOfWork uow = entityManager.unwrap(UnitOfWork.class);
|
||||
DatabaseLogin databaseLogin = uow.getLogin();
|
||||
// Synchronize on shared DatabaseLogin instance for consistent isolation level
|
||||
// set and reset in case of concurrent transactions with different isolation.
|
||||
synchronized (databaseLogin) {
|
||||
int originalIsolationLevel = databaseLogin.getTransactionIsolation();
|
||||
// Apply current isolation level value, if necessary.
|
||||
if (currentIsolationLevel != originalIsolationLevel) {
|
||||
databaseLogin.setTransactionIsolation(currentIsolationLevel);
|
||||
}
|
||||
// Transaction begin including enforced JDBC Connection access
|
||||
// (picking up current isolation level from DatabaseLogin)
|
||||
entityManager.getTransaction().begin();
|
||||
uow.beginEarlyTransaction();
|
||||
entityManager.unwrap(Connection.class);
|
||||
// Restore original isolation level value, if necessary.
|
||||
if (currentIsolationLevel != originalIsolationLevel) {
|
||||
databaseLogin.setTransactionIsolation(originalIsolationLevel);
|
||||
}
|
||||
}
|
||||
uow.getLogin().setTransactionIsolation(definition.getIsolationLevel());
|
||||
}
|
||||
else {
|
||||
entityManager.getTransaction().begin();
|
||||
if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
|
||||
// Begin an early transaction to force EclipseLink to get a JDBC Connection
|
||||
// so that Spring can manage transactions with JDBC as well as EclipseLink.
|
||||
entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
|
||||
}
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
|
||||
if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
|
||||
// Begin an early transaction to force EclipseLink to get a JDBC Connection
|
||||
// so that Spring can manage transactions with JDBC as well as EclipseLink.
|
||||
entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
+3
-15
@@ -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.
|
||||
@@ -27,10 +27,8 @@ import javax.persistence.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.core.testfixture.io.SerializationTestUtils;
|
||||
import org.springframework.jdbc.datasource.DataSourceUtils;
|
||||
import org.springframework.orm.jpa.domain.DriversLicense;
|
||||
import org.springframework.orm.jpa.domain.Person;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatException;
|
||||
@@ -116,34 +114,24 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLazyLoading() throws Exception {
|
||||
public void testLazyLoading() {
|
||||
try {
|
||||
Person tony = new Person();
|
||||
tony.setFirstName("Tony");
|
||||
tony.setLastName("Blair");
|
||||
tony.setDriversLicense(new DriversLicense("8439DK"));
|
||||
sharedEntityManager.persist(tony);
|
||||
assertThat(DataSourceUtils.getConnection(jdbcTemplate.getDataSource()).getTransactionIsolation())
|
||||
.isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED);
|
||||
setComplete();
|
||||
endTransaction();
|
||||
|
||||
transactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
|
||||
startNewTransaction();
|
||||
assertThat(DataSourceUtils.getConnection(jdbcTemplate.getDataSource()).getTransactionIsolation())
|
||||
.isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE);
|
||||
sharedEntityManager.clear();
|
||||
Person newTony = entityManagerFactory.createEntityManager().getReference(Person.class, tony.getId());
|
||||
assertThat(tony).isNotSameAs(newTony);
|
||||
endTransaction();
|
||||
|
||||
transactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
|
||||
startNewTransaction();
|
||||
assertThat(DataSourceUtils.getConnection(jdbcTemplate.getDataSource()).getTransactionIsolation())
|
||||
.isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED);
|
||||
endTransaction();
|
||||
|
||||
assertThat(newTony.getDriversLicense()).isNotNull();
|
||||
|
||||
newTony.getDriversLicense().getSerialNumber();
|
||||
}
|
||||
finally {
|
||||
|
||||
+36
-32
@@ -36,36 +36,41 @@ import org.springframework.transaction.reactive.TransactionSynchronizationManage
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* {@link org.springframework.transaction.ReactiveTransactionManager} implementation
|
||||
* for a single R2DBC {@link ConnectionFactory}. This class is capable of working
|
||||
* in any environment with any R2DBC driver, as long as the setup uses a
|
||||
* {@code ConnectionFactory} as its {@link Connection} factory mechanism.
|
||||
* Binds a R2DBC {@code Connection} from the specified {@code ConnectionFactory}
|
||||
* to the current subscriber context, potentially allowing for one context-bound
|
||||
* {@code Connection} per {@code ConnectionFactory}.
|
||||
* {@link org.springframework.transaction.ReactiveTransactionManager}
|
||||
* implementation for a single R2DBC {@link ConnectionFactory}. This class is
|
||||
* capable of working in any environment with any R2DBC driver, as long as the
|
||||
* setup uses a {@code ConnectionFactory} as its {@link Connection} factory
|
||||
* mechanism. Binds a R2DBC {@code Connection} from the specified
|
||||
* {@code ConnectionFactory} to the current subscriber context, potentially
|
||||
* allowing for one context-bound {@code Connection} per {@code ConnectionFactory}.
|
||||
*
|
||||
* <p><b>Note: The {@code ConnectionFactory} that this transaction manager operates
|
||||
* on needs to return independent {@code Connection}s.</b> The {@code Connection}s
|
||||
* typically come from a connection pool but the {@code ConnectionFactory} must not
|
||||
* return specifically scoped or constrained {@code Connection}s. This transaction
|
||||
* manager will associate {@code Connection} with context-bound transactions,
|
||||
* according to the specified propagation behavior. It assumes that a separate,
|
||||
* independent {@code Connection} can be obtained even during an ongoing transaction.
|
||||
* <p><b>Note: The {@code ConnectionFactory} that this transaction manager
|
||||
* operates on needs to return independent {@code Connection}s.</b>
|
||||
* The {@code Connection}s may come from a pool (the typical case), but the
|
||||
* {@code ConnectionFactory} must not return scoped {@code Connection}s
|
||||
* or the like. This transaction manager will associate {@code Connection}
|
||||
* with context-bound transactions itself, according to the specified propagation
|
||||
* behavior. It assumes that a separate, independent {@code Connection} can
|
||||
* be obtained even during an ongoing transaction.
|
||||
*
|
||||
* <p>Application code is required to retrieve the R2DBC Connection via
|
||||
* {@link ConnectionFactoryUtils#getConnection(ConnectionFactory)}
|
||||
* instead of a standard R2DBC-style {@link ConnectionFactory#create()} call.
|
||||
* Spring classes such as {@code DatabaseClient} use this strategy implicitly.
|
||||
* If not used in combination with this transaction manager, the
|
||||
* {@link ConnectionFactoryUtils} lookup strategy behaves exactly like the native
|
||||
* {@code ConnectionFactory} lookup; it can thus be used in a portable fashion.
|
||||
* {@link ConnectionFactoryUtils} lookup strategy behaves exactly like the
|
||||
* native {@code ConnectionFactory} lookup; it can thus be used in a portable fashion.
|
||||
*
|
||||
* <p>Alternatively, you can allow application code to work with the lookup pattern
|
||||
* {@link ConnectionFactory#create()}, for example for code not aware of Spring.
|
||||
* In that case, define a {@link TransactionAwareConnectionFactoryProxy} for your
|
||||
* target {@code ConnectionFactory}, and pass that proxy {@code ConnectionFactory}
|
||||
* to your DAOs which will automatically participate in Spring-managed transactions
|
||||
* when accessing it.
|
||||
* <p>Alternatively, you can allow application code to work with the standard
|
||||
* R2DBC lookup pattern {@link ConnectionFactory#create()}, for example for code
|
||||
* that is not aware of Spring at all. In that case, define a
|
||||
* {@link TransactionAwareConnectionFactoryProxy} for your target {@code ConnectionFactory},
|
||||
* and pass that proxy {@code ConnectionFactory} to your DAOs, which will automatically
|
||||
* participate in Spring-managed transactions when accessing it.
|
||||
*
|
||||
* <p>This transaction manager triggers flush callbacks on registered transaction
|
||||
* synchronizations (if synchronization is generally active), assuming resources
|
||||
* operating on the underlying R2DBC {@code Connection}.
|
||||
*
|
||||
* @author Mark Paluch
|
||||
* @since 5.3
|
||||
@@ -84,7 +89,7 @@ public class R2dbcTransactionManager extends AbstractReactiveTransactionManager
|
||||
|
||||
/**
|
||||
* Create a new {@code R2dbcTransactionManager} instance.
|
||||
* A {@code ConnectionFactory} has to be set to be able to use it.
|
||||
* A ConnectionFactory has to be set to be able to use it.
|
||||
* @see #setConnectionFactory
|
||||
*/
|
||||
public R2dbcTransactionManager() {}
|
||||
@@ -101,13 +106,12 @@ public class R2dbcTransactionManager extends AbstractReactiveTransactionManager
|
||||
|
||||
|
||||
/**
|
||||
* Set the R2DBC {@link ConnectionFactory} that this instance should manage transactions
|
||||
* for. This will typically be a locally defined {@code ConnectionFactory}, for example
|
||||
* an R2DBC connection pool.
|
||||
* <p><b>The {@code ConnectionFactory} passed in here needs to return independent
|
||||
* {@link Connection}s.</b> The {@code Connection}s typically come from a connection
|
||||
* pool but the {@code ConnectionFactory} must not return specifically scoped or
|
||||
* constrained {@code Connection}s.
|
||||
* Set the R2DBC {@link ConnectionFactory} that this instance should manage transactions for.
|
||||
* <p>This will typically be a locally defined {@code ConnectionFactory}, for example a connection pool.
|
||||
* <p><b>The {@code ConnectionFactory} passed in here needs to return independent {@link Connection}s.</b>
|
||||
* The {@code Connection}s may come from a pool (the typical case), but the {@code ConnectionFactory}
|
||||
* must not return scoped {@code Connection}s or the like.
|
||||
* @see TransactionAwareConnectionFactoryProxy
|
||||
*/
|
||||
public void setConnectionFactory(@Nullable ConnectionFactory connectionFactory) {
|
||||
this.connectionFactory = connectionFactory;
|
||||
@@ -138,8 +142,8 @@ public class R2dbcTransactionManager extends AbstractReactiveTransactionManager
|
||||
* transactional connection: "SET TRANSACTION READ ONLY" as understood by Oracle,
|
||||
* MySQL and Postgres.
|
||||
* <p>The exact treatment, including any SQL statement executed on the connection,
|
||||
* can be customized through {@link #prepareTransactionalConnection}.
|
||||
* @see #prepareTransactionalConnection
|
||||
* can be customized through {@link #prepareTransactionalConnection(Connection, TransactionDefinition)}.
|
||||
* @see #prepareTransactionalConnection(Connection, TransactionDefinition)
|
||||
*/
|
||||
public void setEnforceReadOnly(boolean enforceReadOnly) {
|
||||
this.enforceReadOnly = enforceReadOnly;
|
||||
|
||||
+3
-16
@@ -777,24 +777,11 @@ public class MvcUriComponentsBuilder {
|
||||
|
||||
else if (controllerType.isInterface()) {
|
||||
ClassLoader classLoader = controllerType.getClassLoader();
|
||||
if (classLoader == null) {
|
||||
// JDK bootstrap loader -> use MethodInvocationInfo ClassLoader instead.
|
||||
if (classLoader == null || classLoader.getParent() == null) {
|
||||
// JDK interface type from bootstrap loader or platform loader ->
|
||||
// use higher-level loader which can see Spring infrastructure classes
|
||||
classLoader = MethodInvocationInfo.class.getClassLoader();
|
||||
}
|
||||
else if (classLoader.getParent() == null) {
|
||||
// Potentially the JDK platform loader on JDK 9+
|
||||
ClassLoader miiClassLoader = MethodInvocationInfo.class.getClassLoader();
|
||||
ClassLoader miiParent = miiClassLoader.getParent();
|
||||
while (miiParent != null) {
|
||||
if (classLoader == miiParent) {
|
||||
// Suggested ClassLoader is ancestor of MethodInvocationInfo ClassLoader
|
||||
// -> use MethodInvocationInfo ClassLoader itself instead.
|
||||
classLoader = miiClassLoader;
|
||||
break;
|
||||
}
|
||||
miiParent = miiParent.getParent();
|
||||
}
|
||||
}
|
||||
Class<?>[] ifcs = new Class<?>[] {controllerType, MethodInvocationInfo.class};
|
||||
return (T) Proxy.newProxyInstance(classLoader, ifcs, interceptor);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user