Compare commits

...

69 Commits

Author SHA1 Message Date
Spring Buildmaster 21648426e9 Next Development Version 2020-12-09 08:31:54 +00:00
Juergen Hoeller 0b076b28f1 Remove duplicate "property" in PropertyCacheKey.toString()
Closes gh-26237
2020-12-08 15:14:28 +01:00
Juergen Hoeller 0abb17af9d Polishing (aligned with 5.1.x) 2020-12-08 15:14:08 +01:00
Juergen Hoeller d5a80d2777 Polishing (aligned with 5.2.x) 2020-12-02 17:52:40 +01:00
Rossen Stoyanchev 07455c8a27 ContentCachingResponseWrapper skips contentLength for chunked responses
Closes gh-26182
2020-12-01 20:28:00 +00:00
Juergen Hoeller c45c67203c Add Maven Central repository (aligned with 5.1.x) 2020-11-26 16:10:26 +01:00
Juergen Hoeller aeb83fe1a3 Remove misleading default note on ISO.DATE_TIME
Closes gh-26134

(cherry picked from commit 86f9716fef)
2020-11-26 16:09:13 +01:00
Rossen Stoyanchev 0bf002dbe1 Fix 401 errors from artifactory 2020-11-16 13:49:41 +00:00
Rossen Stoyanchev 4ff521d769 UrlPathHelper.removeJsessionid correctly appends remainder
Closes gh-26079
2020-11-16 11:31:24 +00:00
Juergen Hoeller 9107aed878 Refined SqlParameterSource batchUpdate tests (plus related polishing)
See gh-26071
2020-11-12 14:43:11 +01:00
Juergen Hoeller 4ba174311b Polishing 2020-11-09 14:22:06 +01:00
Juergen Hoeller 09c8586ee4 Polishing 2020-11-05 19:05:47 +01:00
Juergen Hoeller 8212151f16 Suppress NotWritablePropertyException in case of ignoreUnknown=true
Closes gh-25986
2020-11-05 19:05:39 +01:00
Juergen Hoeller 65577671bc Polishing 2020-10-26 18:28:49 +01:00
Rossen Stoyanchev d1d37534bf Reinstate removal of jsessionid from lookup path
Closes gh-25864
2020-10-13 16:55:44 +01:00
Juergen Hoeller 45322a72a5 Polishing 2020-10-13 01:22:39 +02:00
Juergen Hoeller 678ea4ece7 Avoid creation of unused logger instance in AbstractMediaTypeExpression
Closes gh-25901
2020-10-13 01:20:34 +02:00
Juergen Hoeller bacf6ca37b Polishing 2020-10-07 15:03:26 +02:00
Juergen Hoeller 95c0f1108f Construct StringWriter instances with appropriate initial size
Closes gh-25789
2020-10-07 15:02:50 +02:00
Spring Buildmaster 06c76d8075 Next Development Version 2020-09-15 10:51:10 +00:00
Juergen Hoeller 7056dd599f Polishing 2020-09-14 23:46:49 +02:00
Rossen Stoyanchev bb5b12af3b UriComponentsBuilder Javadoc update
Closes gh-25604
2020-09-08 12:30:00 +01:00
Rossen Stoyanchev 2f75212eb6 Avoid unnecessary parsing of path params
Closes gh-25690
2020-09-08 12:24:44 +01:00
Rossen Stoyanchev bdcb189e50 Shared read-only instances of UrlPathHelper
UrlPathHelper is often created and used without customizations or with
the same customizations. This commit introduces re-usable, instances.
Effectively a backport of commit 23233c.

Closes gh-25690
2020-09-08 12:24:27 +01:00
Juergen Hoeller caa22b7291 Properties loading with ignoreResourceNotFound covers SocketException as well
Closes gh-25717
2020-09-07 18:50:16 +02:00
Juergen Hoeller 586677341c Revise documentation notes on getParameterType performance issues
See gh-25679
2020-09-05 14:28:35 +02:00
Juergen Hoeller 2d632eff0f Fix SpEL generated code for default method invocation
Closes gh-25706
2020-09-05 14:28:19 +02:00
Juergen Hoeller eec4a6d521 Retry DatabaseMetaData retrieval if access to transactional connection fails
Closes gh-25681
2020-09-03 23:30:04 +02:00
Juergen Hoeller a577f633ff Polishing 2020-09-01 11:00:18 +02:00
Juergen Hoeller b6677ccbff Polishing 2020-08-27 16:16:24 +02:00
Juergen Hoeller 6c977e9c2a Avoid potential integer overflow in seconds->millis transformation
Closes gh-25613
2020-08-27 15:59:52 +02:00
Juergen Hoeller 265bc6cd65 Populate dependencies metadata for resolved target behind lazy dependency proxy
Closes gh-25562
2020-08-07 22:07:12 +02:00
Juergen Hoeller 3d2de9a378 Efficient concurrency in MethodOverrides through CopyOnWriteArraySet
Closes gh-23448
2020-08-07 15:39:36 +02:00
Juergen Hoeller cc1f0e1186 Polishing 2020-08-07 15:37:04 +02:00
Juergen Hoeller 17a47b30e9 Refine use of substring operations
Closes gh-25445
2020-08-07 15:21:54 +02:00
Juergen Hoeller 5e5723c8ba Reset charset field in MockHttpServletResponse
Closes gh-25501
2020-08-07 15:20:52 +02:00
Sam Brannen 9fcdaa7308 Regression tests for @RestControllerAdvice support in MockMvc
This commit introduces regression tests for @RestControllerAdvice
support in standalone MockMvc configurations.

See gh-25520
2020-08-05 18:56:58 +02:00
Sam Brannen ef6494584c Fix bug in StaticListableBeanFactory.isSingleton()
Prior to this commit, StaticListableBeanFactory.isSingleton() returned
false for singleton beans unless they were created by a FactoryBean.

StaticListableBeanFactory.isSingleton() now properly returns true for
all beans not created by a FactoryBean.

Closes gh-25522
2020-08-04 16:50:14 +02:00
Spring Buildmaster 88f792a5d7 Next Development Version 2020-07-21 06:59:04 +00:00
Juergen Hoeller d8654607a4 Defer creating logger in StandardWebSocketHandlerAdapter to instantiation time
Closes gh-25427

(cherry picked from commit 64f4703445)
2020-07-20 17:21:11 +02:00
Juergen Hoeller 93e42b8e4f Copy queryParams MultiValueMap through deepCopy (for independent List entries)
Closes gh-25423
2020-07-20 08:01:51 +02:00
Rossen Stoyanchev 70773468c2 Align default values with 5.0.x
Closes gh-25414
2020-07-20 06:32:38 +03:00
Juergen Hoeller 6d524e1da5 Unwrap SqlParameterValue for disposable value detection in cleanupParameters
Closes gh-22972
2020-07-19 20:49:05 +02:00
Juergen Hoeller f38ab3863f Polishing 2020-07-17 19:06:14 +02:00
Juergen Hoeller 94d459ebcf Clarify enforceInitMethod/enforceDestroyMethod default values
Closes gh-25402

(cherry picked from commit 5846d9c2ea)
2020-07-17 19:02:46 +02:00
Juergen Hoeller b5887bfd83 Polishing 2020-06-23 11:56:52 +02:00
Juergen Hoeller 299e2c8c46 Avoid misleading log message for commit-triggering exception
Closes gh-25253
2020-06-17 16:25:42 +02:00
Juergen Hoeller 3aae8b2dc8 Polishing 2020-06-12 00:33:46 +02:00
Juergen Hoeller 85e3f23863 Consistent abstract declaration of "Abstract" base classes
Closes gh-25240
2020-06-12 00:33:02 +02:00
Juergen Hoeller 323977be2c Document exception handling limitations in TaskDecorator implementations
Closes gh-25231
2020-06-10 23:08:53 +02:00
Juergen Hoeller 2c1cca69e7 Polishing 2020-06-10 12:19:09 +02:00
Juergen Hoeller 00c9875122 Consistent MultiValueMap behavior for empty list values
Closes gh-25227
2020-06-10 12:17:44 +02:00
Juergen Hoeller 2010956076 WebSphereUowTransactionManager sets timeout for actual transaction only
Closes gh-25225
2020-06-10 12:16:59 +02:00
Juergen Hoeller 9c73023e5a Avoid ClassCastException on IllegalArgumentException from sync invocation
Closes gh-25223
2020-06-10 12:16:19 +02:00
Juergen Hoeller 700fedef3e Consistent not-null assertions for configured interceptors
Closes gh-25221
2020-06-10 12:16:01 +02:00
Juergen Hoeller 31cda09c93 Avoid full synchronization in refreshable getBeanFactory() implementation
Closes gh-25219
2020-06-10 12:15:07 +02:00
Spring Buildmaster 16d4e0e6c4 Next Development Version 2020-04-28 09:27:37 +00:00
Juergen Hoeller 6893207998 Polishing 2020-04-27 14:55:25 +02:00
Rossen Stoyanchev 85c5a0c1a9 Escape quoted filename in HttpHeaders
This is primarily to align with similar changes applied to
ContentDisposition in 5.x.

Closes gh-24580
2020-04-21 08:28:42 +01:00
Sam Brannen f60bb825b0 Retain brackets for IPV6 address in MockHttpServletRequest
According to the Javadoc for ServletRequest's getServerName() method,
when the `Host` header is set, the server name is "the value of the
part before ':' in the Host header value ...". For a value representing
an IPV6 address such as `[::ffff:abcd:abcd]`, the enclosing square
brackets should therefore not be stripped from the enclosed IPV6
address.

However, the changes made in conjunction with gh-16704 introduced a
regression in Spring Framework 4.1 for the getServerName() method in
MockHttpServletRequest by stripping the enclosing brackets from the
IPV6 address in the `Host` header. Similarly, the changes made in
conjunction with gh-20686 introduced a regression in Spring Framework
4.3.13 and 5.0.2 in the getRequestURL() method in
MockHttpServletRequest by delegating to the getServerName() method
which strips the enclosing brackets.

This commit fixes the implementation of getServerName() so that the
enclosing brackets are no longer stripped from an IPV6 address in the
`Host` header. The implementation of getRequestURL() is therefore also
fixed.

In addition, in order to avoid a NullPointerException, the
implementations of getServerName() and getServerPort() now assert that
an IPV6 address present in the `Host` header correctly contains an
opening and closing bracket and throw an IllegalStateException if that
is not the case.

Closes gh-24916
2020-04-17 17:24:52 +02:00
Juergen Hoeller f929109415 Close-suppressing Connection proxy exposes target isClosed() state
Closes gh-24853
2020-04-03 22:00:47 +02:00
Juergen Hoeller eb81337e69 Clear by-type cache in case of no pre-existing bean definition as well
Closes gh-24852
2020-04-03 22:00:42 +02:00
Juergen Hoeller 01ec5d83e6 Polishing 2020-03-24 01:31:58 +01:00
Juergen Hoeller 6e579b0474 Polishing 2020-03-13 23:54:13 +01:00
Juergen Hoeller 322d7bed8a Polishing 2020-02-12 18:20:02 +01:00
Juergen Hoeller ef1be1723e Consistent ROLE_INFRASTRUCTURE declarations for configuration classes
Closes gh-24509
2020-02-12 18:17:20 +01:00
Sam Brannen 2dcce8ca31 Upgrade to Gradle 4.10.2
Due to an upgrade of the Artifactory publication plugin on the CI
server, we need to upgrade the build for 4.3.x to Gradle 4.x.

Closes gh-24392
2020-01-17 18:24:57 +01:00
Sam Brannen 032100ce55 Include Objenesis NOTICE file contents in binary distributions
Closes gh-24326
2020-01-16 10:57:56 +01:00
Spring Buildmaster 444338160e Next Development Version 2020-01-14 11:07:05 +00:00
200 changed files with 1998 additions and 1191 deletions
+7 -44
View File
@@ -1,19 +1,16 @@
buildscript {
repositories {
gradlePluginPortal()
maven { url "https://repo.spring.io/plugins-release" }
}
dependencies {
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.7")
classpath("org.asciidoctor:asciidoctor-gradle-plugin:1.5.2")
classpath("io.spring.gradle:propdeps-plugin:0.0.9.RELEASE")
classpath("io.spring.gradle:docbook-reference-plugin:0.3.1")
classpath("org.asciidoctor:asciidoctor-gradle-plugin:1.5.2")
classpath("ws.antonov.gradle.plugins:gradle-plugin-protobuf:0.9.1")
}
}
plugins {
id "org.sonarqube" version "1.1"
}
ext {
linkHomepage = 'https://projects.spring.io/spring-framework'
linkCi = 'https://build.spring.io/browse/SPR'
@@ -133,7 +130,8 @@ configure(allprojects) { project ->
}
repositories {
maven { url "https://repo.spring.io/libs-release" }
mavenCentral()
maven { url "https://repo.spring.io/libs-spring-framework-build" }
}
dependencies {
@@ -222,12 +220,6 @@ configure(subprojects - project(":spring-build-src")) { subproject ->
jacoco("org.jacoco:org.jacoco.agent:0.7.5.201505241946:runtime")
}
gradle.taskGraph.whenReady {taskGraph ->
if (taskGraph.hasTask(':sonarqube')) {
test.jvmArgs "-javaagent:${configurations.jacoco.asPath}=destfile=${buildDir}/jacoco.exec,includes=org.springframework.*"
}
}
jar {
manifest.attributes["Created-By"] =
"${System.getProperty("java.version")} (${System.getProperty("java.specification.vendor")})"
@@ -1134,20 +1126,6 @@ project("spring-framework-bom") {
}
}
sonarqube {
properties {
property "sonar.projectName", "Spring Framework"
property "sonar.profile", "Spring Framework"
property "sonar.jacoco.reportPath", "${buildDir.name}/jacoco.exec"
property "sonar.links.homepage", linkHomepage
property "sonar.links.ci", linkCi
property "sonar.links.issue", linkIssue
property "sonar.links.scm", linkScmUrl
property "sonar.links.scm_dev", linkScmDevConnection
property "sonar.java.coveragePlugin", "jacoco"
}
}
configure(rootProject) {
description = "Spring Framework"
@@ -1370,9 +1348,9 @@ configure(rootProject) {
archives distZip
}
task wrapper(type: Wrapper) {
wrapper {
description = "Generates gradlew[.bat] scripts"
gradleVersion = "2.14.1"
gradleVersion = "4.10.2"
doLast() {
def gradleOpts = "-XX:MaxMetaspaceSize=1024m -Xmx1024m"
@@ -1388,21 +1366,6 @@ configure(rootProject) {
}
configure([project(':spring-build-src'), project(':spring-framework-bom')]) {
sonarqube {
skipProject = true
}
}
configure(project(':spring-core')) {
sonarqube {
properties {
property "sonar.exclusions",
"src/main/java/org/springframework/cglib/**/*,src/main/java/org/springframework/asm/**/*"
}
}
}
/*
* Support publication of artifacts versioned by topic branch.
* CI builds supply `-P BRANCH_NAME=<TOPIC>` to gradle at build time.
+1 -1
View File
@@ -1 +1 @@
version=4.3.26.BUILD-SNAPSHOT
version=4.3.31.BUILD-SNAPSHOT
+1 -1
View File
@@ -21,7 +21,7 @@ eclipse.classpath.file.whenMerged { classpath ->
def projectName = matcher[0][1]
def path = "/${projectName}"
if(!classpath.entries.find { e -> e instanceof ProjectDependency && e.path == path }) {
def dependency = new ProjectDependency(path, project(":${projectName}").path)
def dependency = new ProjectDependency(path)
dependency.exported = true
classpath.entries.add(dependency)
}
Binary file not shown.
+1 -2
View File
@@ -1,6 +1,5 @@
#Wed Aug 17 21:21:18 CEST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip
Vendored
+17 -9
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
##############################################################################
##
@@ -34,11 +34,11 @@ DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
warn () {
echo "$*"
}
die ( ) {
die () {
echo
echo "$*"
echo
@@ -155,11 +155,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
Vendored
-6
View File
@@ -50,7 +50,6 @@ goto fail
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@@ -61,11 +60,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
@@ -649,7 +649,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
}
if (tokens[currentIndex].endsWith(")")) {
sb.append(tokens[currentIndex].substring(0, tokens[currentIndex].length() - 1));
sb.append(tokens[currentIndex], 0, tokens[currentIndex].length() - 1);
return new PointcutBody(numTokensConsumed, sb.toString().trim());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -212,10 +212,12 @@ public class MethodInvocationProceedingJoinPoint implements ProceedingJoinPoint,
@Override
public String[] getParameterNames() {
if (this.parameterNames == null) {
this.parameterNames = parameterNameDiscoverer.getParameterNames(getMethod());
String[] parameterNames = this.parameterNames;
if (parameterNames == null) {
parameterNames = parameterNameDiscoverer.getParameterNames(getMethod());
this.parameterNames = parameterNames;
}
return this.parameterNames;
return parameterNames;
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -80,9 +80,8 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
new Converter<Method, Annotation>() {
@Override
public Annotation convert(Method method) {
AspectJAnnotation<?> annotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(method);
return (annotation != null ? annotation.getAnnotation() : null);
AspectJAnnotation<?> ann = AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(method);
return (ann != null ? ann.getAnnotation() : null);
}
}));
comparator.addComparator(new ConvertingComparator<Method, String>(
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 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.
@@ -136,14 +136,8 @@ class AspectJPrecedenceComparator implements Comparator<Advisor> {
}
private int getAspectDeclarationOrder(Advisor anAdvisor) {
AspectJPrecedenceInformation precedenceInfo =
AspectJAopUtils.getAspectJPrecedenceInformationFor(anAdvisor);
if (precedenceInfo != null) {
return precedenceInfo.getDeclarationOrder();
}
else {
return 0;
}
AspectJPrecedenceInformation precedenceInfo = AspectJAopUtils.getAspectJPrecedenceInformationFor(anAdvisor);
return (precedenceInfo != null ? precedenceInfo.getDeclarationOrder() : 0);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -30,13 +30,14 @@ public class AdviceEntry implements ParseState.Entry {
/**
* Creates a new instance of the {@link AdviceEntry} class.
* @param kind the kind of advice represented by this entry (before, after, around, etc.)
* Create a new {@code AdviceEntry} instance.
* @param kind the kind of advice represented by this entry (before, after, around)
*/
public AdviceEntry(String kind) {
this.kind = kind;
}
@Override
public String toString() {
return "Advice (" + this.kind + ")";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -30,13 +30,14 @@ public class AdvisorEntry implements ParseState.Entry {
/**
* Creates a new instance of the {@link AdvisorEntry} class.
* Create a new {@code AdvisorEntry} instance.
* @param name the bean name of the advisor
*/
public AdvisorEntry(String name) {
this.name = name;
}
@Override
public String toString() {
return "Advisor '" + this.name + "'";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,12 +61,12 @@ public class AopNamespaceHandler extends NamespaceHandlerSupport {
*/
@Override
public void init() {
// In 2.0 XSD as well as in 2.1 XSD.
// In 2.0 XSD as well as in 2.5+ XSDs
registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());
// Only in 2.0 XSD: moved to context namespace as of 2.1
// Only in 2.0 XSD: moved to context namespace in 2.5+
registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 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.
@@ -34,7 +34,7 @@ public class AspectEntry implements ParseState.Entry {
/**
* Create a new AspectEntry.
* Create a new {@code AspectEntry} instance.
* @param id the id of the aspect element
* @param ref the bean name referenced by this aspect element
*/
@@ -43,6 +43,7 @@ public class AspectEntry implements ParseState.Entry {
this.ref = ref;
}
@Override
public String toString() {
return "Aspect: " + (StringUtils.hasLength(this.id) ? "id='" + this.id + "'" : "ref='" + this.ref + "'");
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -28,14 +28,16 @@ public class PointcutEntry implements ParseState.Entry {
private final String name;
/**
* Creates a new instance of the {@link PointcutEntry} class.
* Create a new {@code PointcutEntry} instance.
* @param name the bean name of the pointcut
*/
public PointcutEntry(String name) {
this.name = name;
}
@Override
public String toString() {
return "Pointcut '" + this.name + "'";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -21,9 +21,7 @@ import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.Interceptor;
@@ -334,11 +332,8 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
// an independent instance of the configuration.
// In this case, no proxy will have an instance of this object's configuration,
// but will have an independent copy.
if (logger.isTraceEnabled()) {
logger.trace("Creating copy of prototype ProxyFactoryBean config: " + this);
}
ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());
// The copy needs a fresh advisor chain, and a fresh TargetSource.
TargetSource targetSource = freshTargetSource();
copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
@@ -349,9 +344,6 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
}
copy.setFrozen(this.freezeProxy);
if (logger.isTraceEnabled()) {
logger.trace("Using ProxyCreatorSupport copy: " + copy);
}
return getProxy(copy.createAopProxy());
}
@@ -438,16 +430,12 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
// Materialize interceptor chain from bean names.
for (String name : this.interceptorNames) {
if (logger.isTraceEnabled()) {
logger.trace("Configuring advisor or advice '" + name + "'");
}
if (name.endsWith(GLOBAL_SUFFIX)) {
if (!(this.beanFactory instanceof ListableBeanFactory)) {
throw new AopConfigException(
"Can only use global advisors or interceptors with a ListableBeanFactory");
}
addGlobalAdvisor((ListableBeanFactory) this.beanFactory,
addGlobalAdvisors((ListableBeanFactory) this.beanFactory,
name.substring(0, name.length() - GLOBAL_SUFFIX.length()));
}
@@ -464,7 +452,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
// Avoid unnecessary creation of prototype bean just for advisor chain initialization.
advice = new PrototypePlaceholderAdvisor(name);
}
addAdvisorOnChainCreation(advice, name);
addAdvisorOnChainCreation(advice);
}
}
}
@@ -487,11 +475,10 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
if (logger.isDebugEnabled()) {
logger.debug("Refreshing bean named '" + pa.getBeanName() + "'");
}
// Replace the placeholder with a fresh prototype instance resulting
// from a getBean() lookup
// Replace the placeholder with a fresh prototype instance resulting from a getBean lookup
if (this.beanFactory == null) {
throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
"- cannot resolve prototype advisor '" + pa.getBeanName() + "'");
throw new IllegalStateException("No BeanFactory available anymore (probably due to " +
"serialization) - cannot resolve prototype advisor '" + pa.getBeanName() + "'");
}
Object bean = this.beanFactory.getBean(pa.getBeanName());
Advisor refreshedAdvisor = namedBeanToAdvisor(bean);
@@ -508,28 +495,26 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
/**
* Add all global interceptors and pointcuts.
*/
private void addGlobalAdvisor(ListableBeanFactory beanFactory, String prefix) {
private void addGlobalAdvisors(ListableBeanFactory beanFactory, String prefix) {
String[] globalAdvisorNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Advisor.class);
String[] globalInterceptorNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Interceptor.class);
List<Object> beans = new ArrayList<Object>(globalAdvisorNames.length + globalInterceptorNames.length);
Map<Object, String> names = new HashMap<Object, String>(beans.size());
for (String name : globalAdvisorNames) {
Object bean = beanFactory.getBean(name);
beans.add(bean);
names.put(bean, name);
}
for (String name : globalInterceptorNames) {
Object bean = beanFactory.getBean(name);
beans.add(bean);
names.put(bean, name);
}
AnnotationAwareOrderComparator.sort(beans);
for (Object bean : beans) {
String name = names.get(bean);
if (name.startsWith(prefix)) {
addAdvisorOnChainCreation(bean, name);
if (globalAdvisorNames.length > 0 || globalInterceptorNames.length > 0) {
List<Object> beans = new ArrayList<Object>(globalAdvisorNames.length + globalInterceptorNames.length);
for (String name : globalAdvisorNames) {
if (name.startsWith(prefix)) {
beans.add(beanFactory.getBean(name));
}
}
for (String name : globalInterceptorNames) {
if (name.startsWith(prefix)) {
beans.add(beanFactory.getBean(name));
}
}
AnnotationAwareOrderComparator.sort(beans);
for (Object bean : beans) {
addAdvisorOnChainCreation(bean);
}
}
}
@@ -540,17 +525,11 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
* Because of these three possibilities, we can't type the signature
* more strongly.
* @param next advice, advisor or target object
* @param name bean name from which we obtained this object in our owning
* bean factory
*/
private void addAdvisorOnChainCreation(Object next, String name) {
private void addAdvisorOnChainCreation(Object next) {
// We need to convert to an Advisor if necessary so that our source reference
// matches what we find from superclass interceptors.
Advisor advisor = namedBeanToAdvisor(next);
if (logger.isTraceEnabled()) {
logger.trace("Adding advisor with name '" + name + "'");
}
addAdvisor(advisor);
addAdvisor(namedBeanToAdvisor(next));
}
/**
@@ -561,9 +540,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
*/
private TargetSource freshTargetSource() {
if (this.targetName == null) {
if (logger.isTraceEnabled()) {
logger.trace("Not refreshing target: Bean name not specified in 'interceptorNames'.");
}
// Not refreshing target: bean name not specified in 'interceptorNames'
return this.targetSource;
}
else {
@@ -591,8 +568,8 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
// We expected this to be an Advisor or Advice,
// but it wasn't. This is a configuration error.
throw new AopConfigException("Unknown advisor type " + next.getClass() +
"; Can only include Advisor or Advice type beans in interceptorNames chain except for last entry," +
"which may also be target or TargetSource", ex);
"; can only include Advisor or Advice type beans in interceptorNames chain " +
"except for last entry which may also be target instance or TargetSource", ex);
}
}
@@ -603,7 +580,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
protected void adviceChanged() {
super.adviceChanged();
if (this.singleton) {
logger.debug("Advice has changed; recaching singleton instance");
logger.debug("Advice has changed; re-caching singleton instance");
synchronized (this) {
this.singletonInstance = null;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 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.
@@ -67,6 +67,7 @@ import java.io.Serializable;
* @since 2.5.2
*/
public abstract aspect AbstractInterfaceDrivenDependencyInjectionAspect extends AbstractDependencyInjectionAspect {
/**
* Select initialization join point as object construction
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 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.
@@ -32,8 +32,8 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport;
* Concrete aspect that uses the {@link Configurable} annotation to identify
* which classes need autowiring.
*
* <p>The bean name to look up will be taken from the {@code &#64;Configurable}
* annotation if specified, otherwise the default bean name to look up will be
* <p>The bean name to look up will be taken from the {@code @Configurable}
* annotation if specified; otherwise, the default bean name to look up will be
* the fully qualified name of the class being configured.
*
* @author Rod Johnson
@@ -47,22 +47,26 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport;
public aspect AnnotationBeanConfigurerAspect extends AbstractInterfaceDrivenDependencyInjectionAspect
implements BeanFactoryAware, InitializingBean, DisposableBean {
private BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport();
private final BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport();
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver());
this.beanConfigurerSupport.setBeanFactory(beanFactory);
}
@Override
public void afterPropertiesSet() {
this.beanConfigurerSupport.afterPropertiesSet();
}
@Override
public void configureBean(Object bean) {
this.beanConfigurerSupport.configureBean(bean);
}
@Override
public void destroy() {
this.beanConfigurerSupport.destroy();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 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.
@@ -36,6 +36,7 @@ import org.springframework.scheduling.config.TaskManagementConfigUtils;
* @see org.springframework.scheduling.annotation.ProxyAsyncConfiguration
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class AspectJAsyncConfiguration extends AbstractAsyncConfiguration {
@Bean(name = TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 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,6 +35,7 @@ import org.springframework.transaction.config.TransactionManagementConfigUtils;
* @see TransactionManagementConfigurationSelector
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class AspectJTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ASPECT_BEAN_NAME)
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -431,9 +431,12 @@ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyA
}
return;
}
else {
throw createNotWritablePropertyException(tokens.canonicalName);
if (this.suppressNotWritablePropertyException) {
// Optimization for common ignoreUnknown=true scenario since the
// exception would be caught and swallowed higher up anyway...
return;
}
throw createNotWritablePropertyException(tokens.canonicalName);
}
Object oldValue = null;
@@ -815,7 +818,6 @@ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyA
* @param propertyPath property path, which may be nested
* @return a property accessor for the target bean
*/
@SuppressWarnings("unchecked") // avoid nested generic
protected AbstractNestablePropertyAccessor getPropertyAccessorForPropertyPath(String propertyPath) {
int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
// Handle nested properties recursively.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 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.
@@ -38,6 +38,8 @@ public abstract class AbstractPropertyAccessor extends TypeConverterSupport impl
private boolean autoGrowNestedPaths = false;
boolean suppressNotWritablePropertyException = false;
@Override
public void setExtractOldValueForEditor(boolean extractOldValueForEditor) {
@@ -87,30 +89,41 @@ public abstract class AbstractPropertyAccessor extends TypeConverterSupport impl
List<PropertyAccessException> propertyAccessExceptions = null;
List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
for (PropertyValue pv : propertyValues) {
try {
// This method may throw any BeansException, which won't be caught
if (ignoreUnknown) {
this.suppressNotWritablePropertyException = true;
}
try {
for (PropertyValue pv : propertyValues) {
// setPropertyValue may throw any BeansException, which won't be caught
// here, if there is a critical failure such as no matching field.
// We can attempt to deal only with less serious exceptions.
setPropertyValue(pv);
}
catch (NotWritablePropertyException ex) {
if (!ignoreUnknown) {
throw ex;
try {
setPropertyValue(pv);
}
// Otherwise, just ignore it and continue...
}
catch (NullValueInNestedPathException ex) {
if (!ignoreInvalid) {
throw ex;
catch (NotWritablePropertyException ex) {
if (!ignoreUnknown) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
// Otherwise, just ignore it and continue...
}
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new LinkedList<PropertyAccessException>();
catch (NullValueInNestedPathException ex) {
if (!ignoreInvalid) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
propertyAccessExceptions.add(ex);
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new LinkedList<PropertyAccessException>();
}
propertyAccessExceptions.add(ex);
}
}
}
finally {
if (ignoreUnknown) {
this.suppressNotWritablePropertyException = false;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -45,8 +45,11 @@ import org.springframework.util.StringUtils;
* Static convenience methods for JavaBeans: for instantiating beans,
* checking bean property types, copying bean properties, etc.
*
* <p>Mainly for use within the framework, but to some degree also
* useful for application classes.
* <p>Mainly for internal use within the framework, but to some degree also
* useful for application classes. Consider
* <a href="https://commons.apache.org/proper/commons-beanutils/">Apache Commons BeanUtils</a>,
* <a href="https://hotelsdotcom.github.io/bull/">BULL - Bean Utils Light Library</a>,
* or similar third-party frameworks for more comprehensive bean utilities.
*
* @author Rod Johnson
* @author Juergen Hoeller
@@ -432,7 +435,8 @@ public abstract class BeanUtils {
return null;
}
}
String editorName = targetType.getName() + "Editor";
String targetTypeName = targetType.getName();
String editorName = targetTypeName + "Editor";
try {
Class<?> editorClass = cl.loadClass(editorName);
if (!PropertyEditor.class.isAssignableFrom(editorClass)) {
@@ -448,7 +452,7 @@ public abstract class BeanUtils {
catch (ClassNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("No property editor [" + editorName + "] found for type " +
targetType.getName() + " according to 'Editor' suffix convention");
targetTypeName + " according to 'Editor' suffix convention");
}
unknownEditorTypes.add(targetType);
return null;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -69,7 +69,7 @@ public class BeanWrapperImpl extends AbstractNestablePropertyAccessor implements
private CachedIntrospectionResults cachedIntrospectionResults;
/**
* The security context used for invoking the property methods
* The security context used for invoking the property methods.
*/
private AccessControlContext acc;
@@ -95,7 +95,7 @@ public class BeanWrapperImpl extends AbstractNestablePropertyAccessor implements
/**
* Create a new BeanWrapperImpl for the given object.
* @param object object wrapped by this BeanWrapper
* @param object the object wrapped by this BeanWrapper
*/
public BeanWrapperImpl(Object object) {
super(object);
@@ -112,7 +112,7 @@ public class BeanWrapperImpl extends AbstractNestablePropertyAccessor implements
/**
* Create a new BeanWrapperImpl for the given object,
* registering a nested path that the object is in.
* @param object object wrapped by this BeanWrapper
* @param object the object wrapped by this BeanWrapper
* @param nestedPath the nested path of the object
* @param rootObject the root object at the top of the path
*/
@@ -123,7 +123,7 @@ public class BeanWrapperImpl extends AbstractNestablePropertyAccessor implements
/**
* Create a new BeanWrapperImpl for the given object,
* registering a nested path that the object is in.
* @param object object wrapped by this BeanWrapper
* @param object the object wrapped by this BeanWrapper
* @param nestedPath the nested path of the object
* @param parent the containing BeanWrapper (must not be {@code null})
*/
@@ -164,7 +164,7 @@ public class BeanWrapperImpl extends AbstractNestablePropertyAccessor implements
}
/**
* Obtain a lazily initializted CachedIntrospectionResults instance
* Obtain a lazily initialized CachedIntrospectionResults instance
* for the wrapped object.
*/
private CachedIntrospectionResults getCachedIntrospectionResults() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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,9 +43,9 @@ import org.springframework.util.StringUtils;
* Internal class that caches JavaBeans {@link java.beans.PropertyDescriptor}
* information for a Java class. Not intended for direct use by application code.
*
* <p>Necessary for own caching of descriptors within the application's
* ClassLoader, rather than rely on the JDK's system-wide BeanInfo cache
* (in order to avoid leaks on ClassLoader shutdown).
* <p>Necessary for Spring's own caching of bean descriptors within the application
* {@link ClassLoader}, rather than relying on the JDK's system-wide {@link BeanInfo}
* cache (in order to avoid leaks on individual application shutdown in a shared JVM).
*
* <p>Information is cached statically, so we don't need to create new
* objects of this class for every JavaBean we manipulate. Hence, this class
@@ -97,7 +97,7 @@ public class CachedIntrospectionResults {
SpringProperties.getFlag(IGNORE_BEANINFO_PROPERTY_NAME);
/** Stores the BeanInfoFactory instances */
private static List<BeanInfoFactory> beanInfoFactories = SpringFactoriesLoader.loadFactories(
private static final List<BeanInfoFactory> beanInfoFactories = SpringFactoriesLoader.loadFactories(
BeanInfoFactory.class, CachedIntrospectionResults.class.getClassLoader());
private static final Log logger = LogFactory.getLog(CachedIntrospectionResults.class);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -51,7 +51,7 @@ public class DirectFieldAccessor extends AbstractNestablePropertyAccessor {
/**
* Create a new DirectFieldAccessor for the given object.
* @param object object wrapped by this DirectFieldAccessor
* @param object the object wrapped by this DirectFieldAccessor
*/
public DirectFieldAccessor(Object object) {
super(object);
@@ -60,7 +60,7 @@ public class DirectFieldAccessor extends AbstractNestablePropertyAccessor {
/**
* Create a new DirectFieldAccessor for the given object,
* registering a nested path that the object is in.
* @param object object wrapped by this DirectFieldAccessor
* @param object the object wrapped by this DirectFieldAccessor
* @param nestedPath the nested path of the object
* @param parent the containing DirectFieldAccessor (must not be {@code null})
*/
@@ -90,8 +90,7 @@ public class DirectFieldAccessor extends AbstractNestablePropertyAccessor {
@Override
protected NotWritablePropertyException createNotWritablePropertyException(String propertyName) {
PropertyMatches matches = PropertyMatches.forField(propertyName, getRootClass());
throw new NotWritablePropertyException(
getRootClass(), getNestedPath() + propertyName,
throw new NotWritablePropertyException(getRootClass(), getNestedPath() + propertyName,
matches.buildErrorMessage(), matches.getPossibleMatches());
}
@@ -516,7 +516,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
if (endIndex != -1) {
String prefix = propertyPath.substring(0, startIndex);
String key = propertyPath.substring(startIndex, endIndex + 1);
String suffix = propertyPath.substring(endIndex + 1, propertyPath.length());
String suffix = propertyPath.substring(endIndex + 1);
// Strip the first key.
strippedPaths.add(nestedPath + prefix + suffix);
// Search for further keys to strip, with the first key stripped.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -37,10 +37,16 @@ package org.springframework.beans.factory;
*
* <p><b>{@code FactoryBean} is a programmatic contract. Implementations are not
* supposed to rely on annotation-driven injection or other reflective facilities.</b>
* {@link #getObjectType()} {@link #getObject()} invocations may arrive early in
* the bootstrap process, even ahead of any post-processor setup. If you need access
* {@link #getObjectType()} {@link #getObject()} invocations may arrive early in the
* bootstrap process, even ahead of any post-processor setup. If you need access to
* other beans, implement {@link BeanFactoryAware} and obtain them programmatically.
*
* <p><b>The container is only responsible for managing the lifecycle of the FactoryBean
* instance, not the lifecycle of the objects created by the FactoryBean.</b> Therefore,
* a destroy method on an exposed bean object (such as {@link java.io.Closeable#close()}
* will <i>not</i> be called automatically. Instead, a FactoryBean should implement
* {@link DisposableBean} and delegate any such close call to the underlying object.
*
* <p>Finally, FactoryBean objects participate in the containing BeanFactory's
* synchronization of bean creation. There is usually no need for internal
* synchronization other than for purposes of lazy initialization within the
@@ -49,6 +55,7 @@ package org.springframework.beans.factory;
* @author Rod Johnson
* @author Juergen Hoeller
* @since 08.03.2003
* @param <T> the bean type
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.aop.framework.ProxyFactoryBean
* @see org.springframework.jndi.JndiObjectFactoryBean
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 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.
@@ -41,12 +41,11 @@ import java.lang.annotation.Target;
* regular constructors: i.e. lookup methods cannot get replaced on beans returned
* from factory methods where we cannot dynamically provide a subclass for them.
*
* <p><b>Concrete limitations in typical Spring configuration scenarios:</b>
* When used with component scanning or any other mechanism that filters out abstract
* beans, provide stub implementations of your lookup methods to be able to declare
* them as concrete classes. And please remember that lookup methods won't work on
* beans returned from {@code @Bean} methods in configuration classes; you'll have
* to resort to {@code @Inject Provider&lt;TargetBean&gt;} or the like instead.
* <p><b>Recommendations for typical Spring configuration scenarios:</b>
* When a concrete class may be needed in certain scenarios, consider providing stub
* implementations of your lookup methods. And please remember that lookup methods
* won't work on beans returned from {@code @Bean} methods in configuration classes;
* you'll have to resort to {@code @Inject Provider<TargetBean>} or the like instead.
*
* @author Juergen Hoeller
* @since 4.1
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 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.
@@ -24,11 +24,11 @@ package org.springframework.beans.factory.parsing;
*/
public class BeanEntry implements ParseState.Entry {
private String beanDefinitionName;
private final String beanDefinitionName;
/**
* Creates a new instance of {@link BeanEntry} class.
* Create a new {@code BeanEntry} instance.
* @param beanDefinitionName the name of the associated bean definition
*/
public BeanEntry(String beanDefinitionName) {
@@ -20,23 +20,17 @@ import java.util.Stack;
/**
* Simple {@link Stack}-based structure for tracking the logical position during
* a parsing process. {@link Entry entries} are added to the stack at
* each point during the parse phase in a reader-specific manner.
* a parsing process. {@link Entry entries} are added to the stack at each point
* during the parse phase in a reader-specific manner.
*
* <p>Calling {@link #toString()} will render a tree-style view of the current logical
* position in the parse phase. This representation is intended for use in
* error messages.
* position in the parse phase. This representation is intended for use in error messages.
*
* @author Rob Harrop
* @since 2.0
*/
public final class ParseState {
/**
* Tab character used when rendering the tree-style representation.
*/
private static final char TAB = '\t';
/**
* Internal {@link Stack} storage.
*/
@@ -51,7 +45,7 @@ public final class ParseState {
}
/**
* Create a new {@code ParseState} whose {@link Stack} is a {@link Object#clone clone}
* Create a new {@code ParseState} whose {@link Stack} is a clone
* of that of the passed in {@code ParseState}.
*/
@SuppressWarnings("unchecked")
@@ -79,7 +73,7 @@ public final class ParseState {
* {@code null} if the {@link Stack} is empty.
*/
public Entry peek() {
return this.state.empty() ? null : this.state.peek();
return (this.state.empty() ? null : this.state.peek());
}
/**
@@ -96,16 +90,18 @@ public final class ParseState {
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int x = 0; x < this.state.size(); x++) {
if (x > 0) {
StringBuilder sb = new StringBuilder(64);
int i = 0;
for (ParseState.Entry entry : this.state) {
if (i > 0) {
sb.append('\n');
for (int y = 0; y < x; y++) {
sb.append(TAB);
for (int j = 0; j < i; j++) {
sb.append('\t');
}
sb.append("-> ");
}
sb.append(this.state.get(x));
sb.append(entry);
i++;
}
return sb.toString();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -30,14 +30,12 @@ public class PropertyEntry implements ParseState.Entry {
/**
* Creates a new instance of the {@link PropertyEntry} class.
* Create a new {@code PropertyEntry} instance.
* @param name the name of the JavaBean property represented by this instance
* @throws IllegalArgumentException if the supplied {@code name} is {@code null}
* or consists wholly of whitespace
*/
public PropertyEntry(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Invalid property name '" + name + "'.");
throw new IllegalArgumentException("Invalid property name '" + name + "'");
}
this.name = name;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -26,16 +26,21 @@ import org.springframework.util.StringUtils;
*/
public class QualifierEntry implements ParseState.Entry {
private String typeName;
private final String typeName;
/**
* Create a new {@code QualifierEntry} instance.
* @param typeName the name of the qualifier type
*/
public QualifierEntry(String typeName) {
if (!StringUtils.hasText(typeName)) {
throw new IllegalArgumentException("Invalid qualifier type '" + typeName + "'.");
throw new IllegalArgumentException("Invalid qualifier type '" + typeName + "'");
}
this.typeName = typeName;
}
@Override
public String toString() {
return "Qualifier '" + this.typeName + "'";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -294,7 +294,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
public void autowireBean(Object existingBean) {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
@@ -314,7 +314,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
if (bd == null) {
bd = new RootBeanDefinition(mbd);
}
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
}
BeanWrapper bw = new BeanWrapperImpl(existingBean);
@@ -337,7 +337,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.setScope(SCOPE_PROTOTYPE);
return createBean(beanClass.getName(), bd, null);
}
@@ -345,7 +345,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.setScope(SCOPE_PROTOTYPE);
if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
}
@@ -378,7 +378,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd =
new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.setScope(SCOPE_PROTOTYPE);
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
populateBean(bd.getBeanClass().getName(), bd, bw);
@@ -584,7 +584,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
@@ -809,16 +809,20 @@ public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccess
}
/**
* Specify whether or not the configured init method is the default.
* <p>The default value is {@code false}.
* Specify whether or not the configured initializer method is the default.
* <p>The default value is {@code true} for a locally specified init method
* but switched to {@code false} for a shared setting in a defaults section
* (e.g. {@code bean init-method} versus {@code beans default-init-method}
* level in XML) which might not apply to all contained bean definitions.
* @see #setInitMethodName
* @see #applyDefaults
*/
public void setEnforceInitMethod(boolean enforceInitMethod) {
this.enforceInitMethod = enforceInitMethod;
}
/**
* Indicate whether the configured init method is the default.
* Indicate whether the configured initializer method is the default.
* @see #getInitMethodName()
*/
public boolean isEnforceInitMethod() {
@@ -842,8 +846,12 @@ public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccess
/**
* Specify whether or not the configured destroy method is the default.
* <p>The default value is {@code false}.
* <p>The default value is {@code true} for a locally specified destroy method
* but switched to {@code false} for a shared setting in a defaults section
* (e.g. {@code bean destroy-method} versus {@code beans default-destroy-method}
* level in XML) which might not apply to all contained bean definitions.
* @see #setDestroyMethodName
* @see #applyDefaults
*/
public void setEnforceDestroyMethod(boolean enforceDestroyMethod) {
this.enforceDestroyMethod = enforceDestroyMethod;
@@ -851,7 +859,7 @@ public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccess
/**
* Indicate whether the configured destroy method is the default.
* @see #getDestroyMethodName
* @see #getDestroyMethodName()
*/
public boolean isEnforceDestroyMethod() {
return this.enforceDestroyMethod;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -879,7 +879,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
/**
* Return whether this factory holds a InstantiationAwareBeanPostProcessor
* that will get applied to singleton beans on shutdown.
* that will get applied to singleton beans on creation.
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
*/
@@ -1280,7 +1280,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
}
@@ -1295,7 +1295,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
mbd.setScope(SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
@@ -1508,7 +1508,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* should be used as fallback.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @return the type for the bean if determinable, or {@code null} else
* @return the type for the bean if determinable, or {@code null} otherwise
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -24,6 +24,7 @@ import org.springframework.util.StringUtils;
* @author Mark Fisher
* @author Juergen Hoeller
* @since 2.5
* @see AbstractBeanDefinition#applyDefaults
*/
public class BeanDefinitionDefaults {
@@ -42,6 +43,7 @@ public class BeanDefinitionDefaults {
* Set whether beans should be lazily initialized by default.
* <p>If {@code false}, the bean will get instantiated on startup by bean
* factories that perform eager initialization of singletons.
* @see AbstractBeanDefinition#setLazyInit
*/
public void setLazyInit(boolean lazyInit) {
this.lazyInit = lazyInit;
@@ -63,6 +65,7 @@ public class BeanDefinitionDefaults {
* (however, there may still be explicit annotation-driven autowiring).
* @param autowireMode the autowire mode to set.
* Must be one of the constants defined in {@link AbstractBeanDefinition}.
* @see AbstractBeanDefinition#setAutowireMode
*/
public void setAutowireMode(int autowireMode) {
this.autowireMode = autowireMode;
@@ -79,6 +82,7 @@ public class BeanDefinitionDefaults {
* Set the dependency check code.
* @param dependencyCheck the code to set.
* Must be one of the constants defined in {@link AbstractBeanDefinition}.
* @see AbstractBeanDefinition#setDependencyCheck
*/
public void setDependencyCheck(int dependencyCheck) {
this.dependencyCheck = dependencyCheck;
@@ -93,6 +97,10 @@ public class BeanDefinitionDefaults {
/**
* Set the name of the default initializer method.
* <p>Note that this method is not enforced on all affected bean definitions
* but rather taken as an optional callback, to be invoked if actually present.
* @see AbstractBeanDefinition#setInitMethodName
* @see AbstractBeanDefinition#setEnforceInitMethod
*/
public void setInitMethodName(String initMethodName) {
this.initMethodName = (StringUtils.hasText(initMethodName) ? initMethodName : null);
@@ -107,6 +115,10 @@ public class BeanDefinitionDefaults {
/**
* Set the name of the default destroy method.
* <p>Note that this method is not enforced on all affected bean definitions
* but rather taken as an optional callback, to be invoked if actually present.
* @see AbstractBeanDefinition#setDestroyMethodName
* @see AbstractBeanDefinition#setEnforceDestroyMethod
*/
public void setDestroyMethodName(String destroyMethodName) {
this.destroyMethodName = (StringUtils.hasText(destroyMethodName) ? destroyMethodName : null);
@@ -90,8 +90,7 @@ import org.springframework.util.StringUtils;
* operating on pre-resolved bean definition metadata objects.
*
* <p>Note that readers for specific bean definition formats are typically
* implemented separately rather than as bean factory subclasses:
* see for example {@link PropertiesBeanDefinitionReader} and
* implemented separately rather than as bean factory subclasses: see for example
* {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}.
*
* <p>For an alternative implementation of the
@@ -179,7 +178,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
private volatile String[] frozenBeanDefinitionNames;
/** Whether bean definition metadata may be cached for all beans */
private volatile boolean configurationFrozen = false;
private volatile boolean configurationFrozen;
/**
@@ -861,6 +860,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
else if (isConfigurationFrozen()) {
clearByTypeCache();
}
}
@Override
@@ -17,9 +17,8 @@
package org.springframework.beans.factory.support;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Set of method overrides, determining which, if any, methods on a
@@ -35,10 +34,7 @@ import java.util.Set;
*/
public class MethodOverrides {
private final Set<MethodOverride> overrides =
Collections.synchronizedSet(new LinkedHashSet<MethodOverride>(0));
private volatile boolean modified = false;
private final Set<MethodOverride> overrides = new CopyOnWriteArraySet<MethodOverride>();
/**
@@ -60,7 +56,6 @@ public class MethodOverrides {
*/
public void addOverrides(MethodOverrides other) {
if (other != null) {
this.modified = true;
this.overrides.addAll(other.overrides);
}
}
@@ -69,17 +64,15 @@ public class MethodOverrides {
* Add the given method override.
*/
public void addOverride(MethodOverride override) {
this.modified = true;
this.overrides.add(override);
}
/**
* Return all method overrides contained by this object.
* @return Set of MethodOverride objects
* @return a Set of MethodOverride objects
* @see MethodOverride
*/
public Set<MethodOverride> getOverrides() {
this.modified = true;
return this.overrides;
}
@@ -87,7 +80,7 @@ public class MethodOverrides {
* Return whether the set of method overrides is empty.
*/
public boolean isEmpty() {
return (!this.modified || this.overrides.isEmpty());
return this.overrides.isEmpty();
}
/**
@@ -96,18 +89,13 @@ public class MethodOverrides {
* @return the method override, or {@code null} if none
*/
public MethodOverride getOverride(Method method) {
if (!this.modified) {
return null;
}
synchronized (this.overrides) {
MethodOverride match = null;
for (MethodOverride candidate : this.overrides) {
if (candidate.matches(method)) {
match = candidate;
}
MethodOverride match = null;
for (MethodOverride candidate : this.overrides) {
if (candidate.matches(method)) {
match = candidate;
}
return match;
}
return match;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -38,7 +38,7 @@ public class ReplaceOverride extends MethodOverride {
private final String methodReplacerBeanName;
private List<String> typeIdentifiers = new LinkedList<String>();
private final List<String> typeIdentifiers = new LinkedList<String>();
/**
@@ -48,7 +48,7 @@ public class ReplaceOverride extends MethodOverride {
*/
public ReplaceOverride(String methodName, String methodReplacerBeanName) {
super(methodName);
Assert.notNull(methodName, "Method replacer bean name must not be null");
Assert.notNull(methodReplacerBeanName, "Method replacer bean name must not be null");
this.methodReplacerBeanName = methodReplacerBeanName;
}
@@ -69,6 +69,7 @@ public class ReplaceOverride extends MethodOverride {
this.typeIdentifiers.add(identifier);
}
@Override
public boolean matches(Method method) {
if (!method.getName().equals(getMethodName())) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -40,20 +40,22 @@ import org.springframework.util.StringUtils;
/**
* Static {@link org.springframework.beans.factory.BeanFactory} implementation
* which allows to register existing singleton instances programmatically.
* Does not have support for prototype beans or aliases.
* which allows one to register existing singleton instances programmatically.
*
* <p>Serves as example for a simple implementation of the
* <p>Does not have support for prototype beans or aliases.
*
* <p>Serves as an example for a simple implementation of the
* {@link org.springframework.beans.factory.ListableBeanFactory} interface,
* managing existing bean instances rather than creating new ones based on bean
* definitions, and not implementing any extended SPI interfaces (such as
* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}).
*
* <p>For a full-fledged factory based on bean definitions, have a look
* at {@link DefaultListableBeanFactory}.
* <p>For a full-fledged factory based on bean definitions, have a look at
* {@link DefaultListableBeanFactory}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @since 06.01.2003
* @see DefaultListableBeanFactory
*/
@@ -78,7 +80,7 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
* or {@link java.util.Collections#emptyMap()} for a dummy factory which
* enforces operating against an empty set of beans.
* @param beans a {@code Map} for holding this factory's beans, with the
* bean name String as key and the corresponding singleton object as value
* bean name as key and the corresponding singleton object as value
* @since 4.3
*/
public StaticListableBeanFactory(Map<String, Object> beans) {
@@ -89,7 +91,7 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
/**
* Add a new singleton bean.
* Will overwrite any existing instance for the given name.
* <p>Will overwrite any existing instance for the given name.
* @param name the name of the bean
* @param bean the bean instance
*/
@@ -182,7 +184,10 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
Object bean = getBean(name);
// In case of FactoryBean, return singleton status of created object.
return (bean instanceof FactoryBean && ((FactoryBean<?>) bean).isSingleton());
if (bean instanceof FactoryBean) {
return ((FactoryBean<?>) bean).isSingleton();
}
return true;
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 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.
@@ -41,6 +41,7 @@ import static org.springframework.tests.TestResourceUtils.*;
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @author Sam Brannen
* @since 04.07.2003
*/
public final class BeanFactoryUtilsTests {
@@ -289,4 +290,111 @@ public final class BeanFactoryUtilsTests {
assertTrue(Arrays.equals(new String[] { "buffer" }, deps));
}
@Test
public void isSingletonAndIsPrototypeWithStaticFactory() {
StaticListableBeanFactory lbf = new StaticListableBeanFactory();
TestBean bean = new TestBean();
DummyFactory fb1 = new DummyFactory();
DummyFactory fb2 = new DummyFactory();
fb2.setSingleton(false);
TestBeanSmartFactoryBean sfb1 = new TestBeanSmartFactoryBean(true, true);
TestBeanSmartFactoryBean sfb2 = new TestBeanSmartFactoryBean(true, false);
TestBeanSmartFactoryBean sfb3 = new TestBeanSmartFactoryBean(false, true);
TestBeanSmartFactoryBean sfb4 = new TestBeanSmartFactoryBean(false, false);
lbf.addBean("bean", bean);
lbf.addBean("fb1", fb1);
lbf.addBean("fb2", fb2);
lbf.addBean("sfb1", sfb1);
lbf.addBean("sfb2", sfb2);
lbf.addBean("sfb3", sfb3);
lbf.addBean("sfb4", sfb4);
Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, true);
assertSame(bean, beans.get("bean"));
assertSame(fb1.getObject(), beans.get("fb1"));
assertTrue(beans.get("fb2") instanceof TestBean);
assertTrue(beans.get("sfb1") instanceof TestBean);
assertTrue(beans.get("sfb2") instanceof TestBean);
assertTrue(beans.get("sfb3") instanceof TestBean);
assertTrue(beans.get("sfb4") instanceof TestBean);
assertEquals(7, lbf.getBeanDefinitionCount());
assertTrue(lbf.getBean("bean") instanceof TestBean);
assertTrue(lbf.getBean("&fb1") instanceof FactoryBean);
assertTrue(lbf.getBean("&fb2") instanceof FactoryBean);
assertTrue(lbf.getBean("&sfb1") instanceof SmartFactoryBean);
assertTrue(lbf.getBean("&sfb2") instanceof SmartFactoryBean);
assertTrue(lbf.getBean("&sfb3") instanceof SmartFactoryBean);
assertTrue(lbf.getBean("&sfb4") instanceof SmartFactoryBean);
assertTrue(lbf.isSingleton("bean"));
assertTrue(lbf.isSingleton("fb1"));
assertTrue(lbf.isSingleton("fb2"));
assertTrue(lbf.isSingleton("sfb1"));
assertTrue(lbf.isSingleton("sfb2"));
assertTrue(lbf.isSingleton("sfb3"));
assertTrue(lbf.isSingleton("sfb4"));
assertTrue(lbf.isSingleton("&fb1"));
assertFalse(lbf.isSingleton("&fb2"));
assertTrue(lbf.isSingleton("&sfb1"));
assertTrue(lbf.isSingleton("&sfb2"));
assertFalse(lbf.isSingleton("&sfb3"));
assertFalse(lbf.isSingleton("&sfb4"));
assertFalse(lbf.isPrototype("bean"));
assertFalse(lbf.isPrototype("fb1"));
assertFalse(lbf.isPrototype("fb2"));
assertFalse(lbf.isPrototype("sfb1"));
assertFalse(lbf.isPrototype("sfb2"));
assertFalse(lbf.isPrototype("sfb3"));
assertFalse(lbf.isPrototype("sfb4"));
assertFalse(lbf.isPrototype("&fb1"));
assertTrue(lbf.isPrototype("&fb2"));
assertTrue(lbf.isPrototype("&sfb1"));
assertFalse(lbf.isPrototype("&sfb2"));
assertTrue(lbf.isPrototype("&sfb3"));
assertTrue(lbf.isPrototype("&sfb4"));
}
static class TestBeanSmartFactoryBean implements SmartFactoryBean<TestBean> {
private final TestBean testBean = new TestBean("enigma", 42);
private final boolean singleton;
private final boolean prototype;
TestBeanSmartFactoryBean(boolean singleton, boolean prototype) {
this.singleton = singleton;
this.prototype = prototype;
}
@Override
public boolean isSingleton() {
return this.singleton;
}
@Override
public boolean isPrototype() {
return this.prototype;
}
@Override
public boolean isEagerInit() {
return false;
}
@Override
public Class<TestBean> getObjectType() {
return TestBean.class;
}
public TestBean getObject() throws Exception {
// We don't really care if the actual instance is a singleton or prototype
// for the tests that use this factory.
return this.testBean;
}
}
}
@@ -1425,6 +1425,39 @@ public class DefaultListableBeanFactoryTests {
lbf.getBean(TestBean.class);
}
@Test
public void testGetBeanByTypeWithLateRegistration() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
try {
lbf.getBean(TestBean.class);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("bd1", bd1);
TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd1"));
}
@Test
public void testGetBeanByTypeWithLateRegistrationAgainstFrozen() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.freezeConfiguration();
try {
lbf.getBean(TestBean.class);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("bd1", bd1);
TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd1"));
}
@Test
public void testGetBeanByTypeDefinedInParent() {
DefaultListableBeanFactory parent = new DefaultListableBeanFactory();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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,6 +35,7 @@ import org.springframework.util.Assert;
* @author Juergen Hoeller
* @author Stephane Nicoll
* @since 4.3
* @see CaffeineCacheManager
*/
@UsesJava8
public class CaffeineCache extends AbstractValueAdaptingCache {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -92,7 +92,6 @@ public class EhCacheCache implements Cache {
this.cache.releaseWriteLockOnKey(key);
}
}
}
private <T> T loadValue(Object key, Callable<T> valueLoader) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 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.
@@ -32,6 +32,7 @@ import org.springframework.cache.transaction.AbstractTransactionSupportingCacheM
* @author Juergen Hoeller
* @author Stephane Nicoll
* @since 3.1
* @see EhCacheCache
*/
public class EhCacheCacheManager extends AbstractTransactionSupportingCacheManager {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -27,13 +27,14 @@ import org.springframework.util.Assert;
/**
* {@link org.springframework.cache.Cache} implementation on top of a
* {@link javax.cache.Cache} instance.
* {@link Cache javax.cache.Cache} instance.
*
* <p>Note: This class has been updated for JCache 1.0, as of Spring 4.0.
*
* @author Juergen Hoeller
* @author Stephane Nicoll
* @since 3.2
* @see JCacheCacheManager
*/
public class JCacheCache extends AbstractValueAdaptingCache {
@@ -41,7 +42,7 @@ public class JCacheCache extends AbstractValueAdaptingCache {
/**
* Create an {@link org.springframework.cache.jcache.JCacheCache} instance.
* Create a {@code JCacheCache} instance.
* @param jcache backing JCache Cache instance
*/
public JCacheCache(Cache<Object, Object> jcache) {
@@ -49,7 +50,7 @@ public class JCacheCache extends AbstractValueAdaptingCache {
}
/**
* Create an {@link org.springframework.cache.jcache.JCacheCache} instance.
* Create a {@code JCacheCache} instance.
* @param jcache backing JCache Cache instance
* @param allowNullValues whether to accept and convert null values for this cache
*/
@@ -123,7 +124,7 @@ public class JCacheCache extends AbstractValueAdaptingCache {
}
catch (Exception ex) {
throw new EntryProcessorException("Value loader '" + valueLoader + "' failed " +
"to compute value for key '" + entry.getKey() + "'", ex);
"to compute value for key '" + entry.getKey() + "'", ex);
}
entry.setValue(toStoreValue(value));
return value;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -26,7 +26,7 @@ import org.springframework.cache.transaction.AbstractTransactionSupportingCacheM
/**
* {@link org.springframework.cache.CacheManager} implementation
* backed by a JCache {@link javax.cache.CacheManager}.
* backed by a JCache {@link CacheManager javax.cache.CacheManager}.
*
* <p>Note: This class has been updated for JCache 1.0, as of Spring 4.0.
*
@@ -42,15 +42,18 @@ public class JCacheCacheManager extends AbstractTransactionSupportingCacheManage
/**
* Create a new JCacheCacheManager, setting the target JCache CacheManager
* through the {@link #setCacheManager} bean property.
* Create a new {@code JCacheCacheManager} without a backing JCache
* {@link CacheManager javax.cache.CacheManager}.
* <p>The backing JCache {@code javax.cache.CacheManager} can be set via the
* {@link #setCacheManager} bean property.
*/
public JCacheCacheManager() {
}
/**
* Create a new JCacheCacheManager for the given backing JCache.
* @param cacheManager the backing JCache {@link javax.cache.CacheManager}
* Create a new {@code JCacheCacheManager} for the given backing JCache
* {@link CacheManager javax.cache.CacheManager}.
* @param cacheManager the backing JCache {@code javax.cache.CacheManager}
*/
public JCacheCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
@@ -58,14 +61,14 @@ public class JCacheCacheManager extends AbstractTransactionSupportingCacheManage
/**
* Set the backing JCache {@link javax.cache.CacheManager}.
* Set the backing JCache {@link CacheManager javax.cache.CacheManager}.
*/
public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
/**
* Return the backing JCache {@link javax.cache.CacheManager}.
* Return the backing JCache {@link CacheManager javax.cache.CacheManager}.
*/
public CacheManager getCacheManager() {
return this.cacheManager;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 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,7 +35,7 @@ import org.springframework.context.annotation.Role;
* @see JCacheConfigurer
*/
@Configuration
public class AbstractJCacheConfiguration extends AbstractCachingConfiguration {
public abstract class AbstractJCacheConfiguration extends AbstractCachingConfiguration {
protected CacheResolver exceptionCacheResolver;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -56,9 +56,9 @@ import org.springframework.util.concurrent.ListenableFutureTask;
* <p>The CommonJ WorkManager will usually be retrieved from the application
* server's JNDI environment, as defined in the server's management console.
*
* <p>Note: On the upcoming EE 7 compliant versions of WebLogic and WebSphere, a
* <p>Note: On EE 7/8 compliant versions of WebLogic and WebSphere, a
* {@link org.springframework.scheduling.concurrent.DefaultManagedTaskExecutor}
* should be preferred, following JSR-236 support in Java EE 7.
* should be preferred, following JSR-236 support in Java EE 7/8.
*
* @author Juergen Hoeller
* @since 2.0
@@ -112,6 +112,11 @@ public class WorkManagerTaskExecutor extends JndiLocatorSupport
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* is limited to plain {@code Runnable} execution via {@code execute} calls.
* In case of {@code #submit} calls, the exposed {@code Runnable} will be a
* {@code FutureTask} which does not propagate any exceptions; you might
* have to cast it and call {@code Future#get} to evaluate exceptions.
* @since 4.3
*/
public void setTaskDecorator(TaskDecorator taskDecorator) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 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.
@@ -46,7 +46,7 @@ public abstract class FreeMarkerTemplateUtils {
public static String processTemplateIntoString(Template template, Object model)
throws IOException, TemplateException {
StringWriter result = new StringWriter();
StringWriter result = new StringWriter(1024);
template.process(model, result);
return result.toString();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -50,6 +50,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
@@ -365,9 +366,9 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker
}));
}
catch (Cache.ValueRetrievalException ex) {
// The invoker wraps any Throwable in a ThrowableWrapper instance so we
// can just make sure that one bubbles up the stack.
throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause();
// Directly propagate ThrowableWrapper from the invoker,
// or potentially also an IllegalArgumentException etc.
ReflectionUtils.rethrowRuntimeException(ex.getCause());
}
}
else {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -53,8 +53,7 @@ public abstract class AbstractValueAdaptingCache implements Cache {
@Override
public ValueWrapper get(Object key) {
Object value = lookup(key);
return toValueWrapper(value);
return toValueWrapper(lookup(key));
}
@Override
@@ -113,5 +112,4 @@ public abstract class AbstractValueAdaptingCache implements Cache {
return (storeValue != null ? new SimpleValueWrapper(fromStoreValue(storeValue)) : null);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -29,6 +29,7 @@ import org.springframework.util.Assert;
* @author Costin Leau
* @author Stephane Nicoll
* @since 4.3.4
* @see NoOpCacheManager
*/
public class NoOpCache implements Cache {
@@ -36,7 +37,7 @@ public class NoOpCache implements Cache {
/**
* Create a {@link NoOpCache} instance with the specified name
* Create a {@link NoOpCache} instance with the specified name.
* @param name the name of the cache
*/
public NoOpCache(String name) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 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.
@@ -36,7 +36,7 @@ import org.springframework.cache.CacheManager;
* @author Costin Leau
* @author Stephane Nicoll
* @since 3.1
* @see CompositeCacheManager
* @see NoOpCache
*/
public class NoOpCacheManager implements CacheManager {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -147,11 +147,12 @@ public interface ConfigurableApplicationContext extends ApplicationContext, Life
void addProtocolResolver(ProtocolResolver resolver);
/**
* Load or refresh the persistent representation of the configuration,
* which might an XML file, properties file, or relational database schema.
* Load or refresh the persistent representation of the configuration, which
* might be from Java-based configuration, an XML file, a properties file, a
* relational database schema, or some other format.
* <p>As this is a startup method, it should destroy already created singletons
* if it fails, to avoid dangling resources. In other words, after invocation
* of that method, either all or no singletons at all should be instantiated.
* of this method, either all or no singletons at all should be instantiated.
* @throws BeansException if the bean factory could not be initialized
* @throws IllegalStateException if already initialized and multiple refresh
* attempts are not supported
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -33,7 +33,8 @@ import org.springframework.core.type.AnnotationMetadata;
*
* @author Chris Beams
* @since 3.1
* @see EnableAspectJAutoProxy
* @see org.springframework.cache.annotation.EnableCaching
* @see org.springframework.transaction.annotation.EnableTransactionManagement
*/
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -343,15 +343,16 @@ import org.springframework.stereotype.Component;
*
* <p>By default, {@code @Bean} methods will be <em>eagerly instantiated</em> at container
* bootstrap time. To avoid this, {@code @Configuration} may be used in conjunction with
* the {@link Lazy @Lazy} annotation to indicate that all {@code @Bean} methods declared within
* the class are by default lazily initialized. Note that {@code @Lazy} may be used on
* individual {@code @Bean} methods as well.
* the {@link Lazy @Lazy} annotation to indicate that all {@code @Bean} methods declared
* within the class are by default lazily initialized. Note that {@code @Lazy} may be used
* on individual {@code @Bean} methods as well.
*
* <h2>Testing support for {@code @Configuration} classes</h2>
*
* <p>The Spring <em>TestContext framework</em> available in the {@code spring-test} module
* provides the {@code @ContextConfiguration} annotation which can accept an array of
* {@code @Configuration} {@code Class} objects:
* <em>component class</em> references &mdash; typically {@code @Configuration} or
* {@code @Component} classes.
*
* <pre class="code">
* &#064;RunWith(SpringRunner.class)
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.context.annotation;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -458,7 +459,8 @@ class ConfigurationClassParser {
catch (IOException ex) {
// Resource not found when trying to open it
if (ignoreResourceNotFound &&
(ex instanceof FileNotFoundException || ex instanceof UnknownHostException)) {
(ex instanceof FileNotFoundException || ex instanceof UnknownHostException ||
ex instanceof SocketException)) {
if (logger.isInfoEnabled()) {
logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
}
@@ -473,32 +475,35 @@ class ConfigurationClassParser {
private void addPropertySource(PropertySource<?> propertySource) {
String name = propertySource.getName();
MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
if (this.propertySourceNames.contains(name)) {
// We've already added a version, we need to extend it
PropertySource<?> existing = propertySources.get(name);
PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
((ResourcePropertySource) propertySource).withResourceName() : propertySource);
if (existing instanceof CompositePropertySource) {
((CompositePropertySource) existing).addFirstPropertySource(newSource);
}
else {
if (existing instanceof ResourcePropertySource) {
existing = ((ResourcePropertySource) existing).withResourceName();
if (existing != null) {
PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
((ResourcePropertySource) propertySource).withResourceName() : propertySource);
if (existing instanceof CompositePropertySource) {
((CompositePropertySource) existing).addFirstPropertySource(newSource);
}
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(newSource);
composite.addPropertySource(existing);
propertySources.replace(name, composite);
else {
if (existing instanceof ResourcePropertySource) {
existing = ((ResourcePropertySource) existing).withResourceName();
}
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(newSource);
composite.addPropertySource(existing);
propertySources.replace(name, composite);
}
return;
}
}
if (this.propertySourceNames.isEmpty()) {
propertySources.addLast(propertySource);
}
else {
if (this.propertySourceNames.isEmpty()) {
propertySources.addLast(propertySource);
}
else {
String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
propertySources.addBefore(firstProcessed, propertySource);
}
String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
propertySources.addBefore(firstProcessed, propertySource);
}
this.propertySourceNames.add(name);
}
@@ -675,7 +680,7 @@ class ConfigurationClassParser {
}
/**
* Factory method to obtain {@link SourceClass}s from class names.
* Factory method to obtain a {@link SourceClass} collection from class names.
*/
private Collection<SourceClass> asSourceClasses(String[] classNames) throws IOException {
List<SourceClass> annotatedClasses = new ArrayList<SourceClass>(classNames.length);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -20,12 +20,14 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver;
import org.springframework.beans.factory.config.DependencyDescriptor;
@@ -71,9 +73,11 @@ public class ContextAnnotationAutowireCandidateResolver extends QualifierAnnotat
}
protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, final String beanName) {
Assert.state(getBeanFactory() instanceof DefaultListableBeanFactory,
BeanFactory beanFactory = getBeanFactory();
Assert.state(beanFactory instanceof DefaultListableBeanFactory,
"BeanFactory needs to be a DefaultListableBeanFactory");
final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
final DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory;
TargetSource ts = new TargetSource() {
@Override
public Class<?> getTargetClass() {
@@ -85,34 +89,43 @@ public class ContextAnnotationAutowireCandidateResolver extends QualifierAnnotat
}
@Override
public Object getTarget() {
Object target = beanFactory.doResolveDependency(descriptor, beanName, null, null);
Set<String> autowiredBeanNames = (beanName != null ? new LinkedHashSet<String>(1) : null);
Object target = dlbf.doResolveDependency(descriptor, beanName, autowiredBeanNames, null);
if (target == null) {
Class<?> type = getTargetClass();
if (Map.class == type) {
return Collections.EMPTY_MAP;
return Collections.emptyMap();
}
else if (List.class == type) {
return Collections.EMPTY_LIST;
return Collections.emptyList();
}
else if (Set.class == type || Collection.class == type) {
return Collections.EMPTY_SET;
return Collections.emptySet();
}
throw new NoSuchBeanDefinitionException(descriptor.getResolvableType(),
"Optional dependency not present for lazy injection point");
}
if (autowiredBeanNames != null) {
for (String autowiredBeanName : autowiredBeanNames) {
if (dlbf.containsBean(autowiredBeanName)) {
dlbf.registerDependentBean(autowiredBeanName, beanName);
}
}
}
return target;
}
@Override
public void releaseTarget(Object target) {
}
};
ProxyFactory pf = new ProxyFactory();
pf.setTargetSource(ts);
Class<?> dependencyType = descriptor.getDependencyType();
if (dependencyType.isInterface()) {
pf.addInterface(dependencyType);
}
return pf.getProxy(beanFactory.getBeanClassLoader());
return pf.getProxy(dlbf.getBeanClassLoader());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 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.
@@ -50,6 +50,7 @@ public interface ImportSelector {
/**
* Select and return the names of which class(es) should be imported based on
* the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
* @return the class names, or an empty array if none
*/
String[] selectImports(AnnotationMetadata importingClassMetadata);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -40,6 +40,7 @@ import org.springframework.instrument.classloading.LoadTimeWeaver;
* @see ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class LoadTimeWeavingConfiguration implements ImportAware, BeanClassLoaderAware {
private AnnotationAttributes enableLTW;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -47,6 +47,7 @@ import org.springframework.util.StringUtils;
* @see EnableMBeanExport
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class MBeanExportConfiguration implements ImportAware, EnvironmentAware, BeanFactoryAware {
private static final String MBEAN_EXPORTER_BEAN_NAME = "mbeanExporter";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -54,25 +54,30 @@ import org.springframework.core.io.support.PropertySourceFactory;
* }
* }</pre>
*
* Notice that the {@code Environment} object is
* <p>Notice that the {@code Environment} object is
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired} into the
* configuration class and then used when populating the {@code TestBean} object. Given
* the configuration above, a call to {@code testBean.getName()} will return "myTestBean".
*
* <h3>Resolving ${...} placeholders in {@code <bean>} and {@code @Value} annotations</h3>
* <h3>Resolving <code>${...}</code> placeholders in {@code <bean>} and {@code @Value} annotations</h3>
*
* In order to resolve ${...} placeholders in {@code <bean>} definitions or {@code @Value}
* annotations using properties from a {@code PropertySource}, one must register
* a {@code PropertySourcesPlaceholderConfigurer}. This happens automatically when using
* {@code <context:property-placeholder>} in XML, but must be explicitly registered using
* a {@code static} {@code @Bean} method when using {@code @Configuration} classes. See
* the "Working with externalized values" section of @{@link Configuration}'s javadoc and
* "a note on BeanFactoryPostProcessor-returning @Bean methods" of @{@link Bean}'s javadoc
* for details and examples.
* <p>In order to resolve ${...} placeholders in {@code <bean>} definitions or {@code @Value}
* annotations using properties from a {@code PropertySource}, you must ensure that an
* appropriate <em>embedded value resolver</em> is registered in the {@code BeanFactory}
* used by the {@code ApplicationContext}. This happens automatically when using
* {@code <context:property-placeholder>} in XML. When using {@code @Configuration} classes
* this can be achieved by explicitly registering a {@code PropertySourcesPlaceholderConfigurer}
* via a {@code static} {@code @Bean} method. Note, however, that explicit registration
* of a {@code PropertySourcesPlaceholderConfigurer} via a {@code static} {@code @Bean}
* method is typically only required if you need to customize configuration such as the
* placeholder syntax, etc. See the "Working with externalized values" section of
* {@link Configuration @Configuration}'s javadocs and "a note on
* BeanFactoryPostProcessor-returning {@code @Bean} methods" of {@link Bean @Bean}'s
* javadocs for details and examples.
*
* <h3>Resolving ${...} placeholders within {@code @PropertySource} resource locations</h3>
*
* Any ${...} placeholders present in a {@code @PropertySource} {@linkplain #value()
* <p>Any ${...} placeholders present in a {@code @PropertySource} {@linkplain #value()
* resource location} will be resolved against the set of property sources already
* registered against the environment. For example:
*
@@ -92,7 +97,7 @@ import org.springframework.core.io.support.PropertySourceFactory;
* }
* }</pre>
*
* Assuming that "my.placeholder" is present in one of the property sources already
* <p>Assuming that "my.placeholder" is present in one of the property sources already
* registered, e.g. system properties or environment variables, the placeholder will
* be resolved to the corresponding value. If not, then "default/path" will be used as a
* default. Expressing a default value (delimited by colon ":") is optional. If no
@@ -101,10 +106,10 @@ import org.springframework.core.io.support.PropertySourceFactory;
*
* <h3>A note on property overriding with @PropertySource</h3>
*
* In cases where a given property key exists in more than one {@code .properties}
* <p>In cases where a given property key exists in more than one {@code .properties}
* file, the last {@code @PropertySource} annotation processed will 'win' and override.
*
* For example, given two properties files {@code a.properties} and
* <p>For example, given two properties files {@code a.properties} and
* {@code b.properties}, consider the following two configuration classes
* that reference them with {@code @PropertySource} annotations:
*
@@ -118,7 +123,7 @@ import org.springframework.core.io.support.PropertySourceFactory;
* public class ConfigB { }
* </pre>
*
* The override ordering depends on the order in which these classes are registered
* <p>The override ordering depends on the order in which these classes are registered
* with the application context.
*
* <pre class="code">
@@ -128,12 +133,12 @@ import org.springframework.core.io.support.PropertySourceFactory;
* ctx.refresh();
* </pre>
*
* In the scenario above, the properties in {@code b.properties} will override any
* <p>In the scenario above, the properties in {@code b.properties} will override any
* duplicates that exist in {@code a.properties}, because {@code ConfigB} was registered
* last.
*
* <p>In certain situations, it may not be possible or practical to tightly control
* property source ordering when using {@code @ProperySource} annotations. For example,
* property source ordering when using {@code @PropertySource} annotations. For example,
* if the {@code @Configuration} classes above were registered via component-scanning,
* the ordering is difficult to predict. In such cases - and if overriding is important -
* it is recommended that the user fall back to using the programmatic PropertySource API.
@@ -150,6 +155,7 @@ import org.springframework.core.io.support.PropertySourceFactory;
* @author Chris Beams
* @author Juergen Hoeller
* @author Phillip Webb
* @author Sam Brannen
* @since 3.1
* @see PropertySources
* @see Configuration
@@ -164,8 +170,11 @@ import org.springframework.core.io.support.PropertySourceFactory;
public @interface PropertySource {
/**
* Indicate the name of this property source. If omitted, a name will
* be generated based on the description of the underlying resource.
* Indicate the name of this property source. If omitted, the {@link #factory()}
* will generate a name based on the underlying resource (in the case of
* {@link org.springframework.core.io.support.DefaultPropertySourceFactory}:
* derived from the resource description through a corresponding name-less
* {@link org.springframework.core.io.support.ResourcePropertySource} constructor).
* @see org.springframework.core.env.PropertySource#getName()
* @see org.springframework.core.io.Resource#getDescription()
*/
@@ -173,8 +182,9 @@ public @interface PropertySource {
/**
* Indicate the resource location(s) of the properties file to be loaded.
* For example, {@code "classpath:/com/myco/app.properties"} or
* {@code "file:/path/to/file"}.
* <p>Both traditional and XML-based properties file formats are supported
* &mdash; for example, {@code "classpath:/com/myco/app.properties"}
* or {@code "file:/path/to/file.xml"}.
* <p>Resource location wildcards (e.g. *&#42;/*.properties) are not permitted;
* each location must evaluate to exactly one {@code .properties} resource.
* <p>${...} placeholders will be resolved against any/all property sources already
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 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,7 @@ public abstract class AbstractRefreshableApplicationContext extends AbstractAppl
private Boolean allowCircularReferences;
/** Bean factory for this context */
private DefaultListableBeanFactory beanFactory;
/** Synchronization monitor for the internal BeanFactory */
private final Object beanFactoryMonitor = new Object();
private volatile DefaultListableBeanFactory beanFactory;
/**
@@ -127,9 +124,7 @@ public abstract class AbstractRefreshableApplicationContext extends AbstractAppl
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
@@ -138,17 +133,18 @@ public abstract class AbstractRefreshableApplicationContext extends AbstractAppl
@Override
protected void cancelRefresh(BeansException ex) {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory != null)
this.beanFactory.setSerializationId(null);
DefaultListableBeanFactory beanFactory = this.beanFactory;
if (beanFactory != null) {
beanFactory.setSerializationId(null);
}
super.cancelRefresh(ex);
}
@Override
protected final void closeBeanFactory() {
synchronized (this.beanFactoryMonitor) {
this.beanFactory.setSerializationId(null);
DefaultListableBeanFactory beanFactory = this.beanFactory;
if (beanFactory != null) {
beanFactory.setSerializationId(null);
this.beanFactory = null;
}
}
@@ -158,20 +154,17 @@ public abstract class AbstractRefreshableApplicationContext extends AbstractAppl
* i.e. has been refreshed at least once and not been closed yet.
*/
protected final boolean hasBeanFactory() {
synchronized (this.beanFactoryMonitor) {
return (this.beanFactory != null);
}
return (this.beanFactory != null);
}
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
DefaultListableBeanFactory beanFactory = this.beanFactory;
if (beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return beanFactory;
}
/**
@@ -173,7 +173,7 @@ public abstract class AbstractResourceBasedMessageSource extends AbstractMessage
* a non-classpath location.
*/
public void setCacheSeconds(int cacheSeconds) {
this.cacheMillis = (cacheSeconds * 1000);
this.cacheMillis = cacheSeconds * 1000L;
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 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.
@@ -24,7 +24,9 @@ import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import static org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.*;
import static org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.DEFAULT_VALUE;
import static org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.LAZY_INIT_ATTRIBUTE;
import static org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.TRUE_VALUE;
/**
* Abstract base class for BeanDefinitionParsers which build
@@ -47,8 +49,9 @@ abstract class AbstractJndiLocatingBeanDefinitionParser extends AbstractSimpleBe
@Override
protected boolean isEligibleAttribute(String attributeName) {
return (super.isEligibleAttribute(attributeName) && !ENVIRONMENT_REF.equals(attributeName) && !LAZY_INIT_ATTRIBUTE
.equals(attributeName));
return (super.isEligibleAttribute(attributeName) &&
!ENVIRONMENT_REF.equals(attributeName) &&
!LAZY_INIT_ATTRIBUTE.equals(attributeName));
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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,6 @@ public @interface DateTimeFormat {
/**
* The most common ISO DateTime Format {@code yyyy-MM-dd'T'HH:mm:ss.SSSZ},
* e.g. "2000-10-31T01:30:00.000-05:00".
* <p>This is the default if no annotation value is specified.
*/
DATE_TIME,
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 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.
@@ -22,7 +22,7 @@ package org.springframework.jmx.export.metadata;
* @author Rob Harrop
* @since 1.2
*/
public class AbstractJmxAttribute {
public abstract class AbstractJmxAttribute {
private String description = "";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -136,6 +136,11 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* is limited to plain {@code Runnable} execution via {@code execute} calls.
* In case of {@code #submit} calls, the exposed {@code Runnable} will be a
* {@code FutureTask} which does not propagate any exceptions; you might
* have to cast it and call {@code Future#get} to evaluate exceptions.
* @since 4.3
*/
public final void setTaskDecorator(TaskDecorator taskDecorator) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 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.
@@ -26,7 +26,7 @@ import org.springframework.jndi.JndiTemplate;
/**
* JNDI-based variant of {@link ConcurrentTaskExecutor}, performing a default lookup for
* JSR-236's "java:comp/DefaultManagedExecutorService" in a Java EE 7 environment.
* JSR-236's "java:comp/DefaultManagedExecutorService" in a Java EE 7/8 environment.
*
* <p>Note: This class is not strictly JSR-236 based; it can work with any regular
* {@link java.util.concurrent.Executor} that can be found in JNDI.
@@ -35,10 +35,11 @@ import org.springframework.jndi.JndiTemplate;
*
* @author Juergen Hoeller
* @since 4.0
* @see javax.enterprise.concurrent.ManagedExecutorService
*/
public class DefaultManagedTaskExecutor extends ConcurrentTaskExecutor implements InitializingBean {
private JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
private final JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
private String jndiName = "java:comp/DefaultManagedExecutorService";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 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,10 +35,11 @@ import org.springframework.jndi.JndiTemplate;
*
* @author Juergen Hoeller
* @since 4.0
* @see javax.enterprise.concurrent.ManagedScheduledExecutorService
*/
public class DefaultManagedTaskScheduler extends ConcurrentTaskScheduler implements InitializingBean {
private JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
private final JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
private String jndiName = "java:comp/DefaultManagedScheduledExecutorService";
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -196,6 +196,13 @@ public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* is limited to plain {@code Runnable} execution via {@code execute} calls.
* In case of {@code #submit} calls, the exposed {@code Runnable} will be a
* {@code FutureTask} which does not propagate any exceptions; you might
* have to cast it and call {@code Future#get} to evaluate exceptions.
* See the {@code ThreadPoolExecutor#afterExecute} javadoc for an example
* of how to access exceptions in such a {@code Future} case.
* @since 4.3
*/
public void setTaskDecorator(TaskDecorator taskDecorator) {
@@ -98,8 +98,8 @@ public class TaskExecutorFactoryBean implements
int maxPoolSize;
int separatorIndex = this.poolSize.indexOf('-');
if (separatorIndex != -1) {
corePoolSize = Integer.valueOf(this.poolSize.substring(0, separatorIndex));
maxPoolSize = Integer.valueOf(this.poolSize.substring(separatorIndex + 1, this.poolSize.length()));
corePoolSize = Integer.parseInt(this.poolSize.substring(0, separatorIndex));
maxPoolSize = Integer.parseInt(this.poolSize.substring(separatorIndex + 1));
if (corePoolSize > maxPoolSize) {
throw new IllegalArgumentException(
"Lower bound of pool-size range must not exceed the upper bound");
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,9 +25,11 @@ import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ObjectUtils;
import static org.junit.Assert.*;
@@ -47,14 +49,18 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests {
ac.registerBeanDefinition("testBean", tbd);
ac.refresh();
ConfigurableListableBeanFactory bf = ac.getBeanFactory();
TestBeanHolder bean = ac.getBean("annotatedBean", TestBeanHolder.class);
assertFalse(ac.getBeanFactory().containsSingleton("testBean"));
assertFalse(bf.containsSingleton("testBean"));
assertNotNull(bean.getTestBean());
assertNull(bean.getTestBean().getName());
assertTrue(ac.getBeanFactory().containsSingleton("testBean"));
assertTrue(bf.containsSingleton("testBean"));
TestBean tb = (TestBean) ac.getBean("testBean");
tb.setName("tb");
assertSame("tb", bean.getTestBean().getName());
assertTrue(ObjectUtils.containsElement(bf.getDependenciesForBean("annotatedBean"), "testBean"));
assertTrue(ObjectUtils.containsElement(bf.getDependentBeans("testBean"), "annotatedBean"));
}
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -119,7 +119,7 @@ public class SimpleNamingContext implements Context {
if (logger.isDebugEnabled()) {
logger.debug("Static JNDI lookup: [" + name + "]");
}
if ("".equals(name)) {
if (name.isEmpty()) {
return new SimpleNamingContext(this.root, this.boundObjects, this.environment);
}
Object found = this.boundObjects.get(name);
@@ -293,12 +293,12 @@ public class SimpleNamingContext implements Context {
}
private static abstract class AbstractNamingEnumeration<T> implements NamingEnumeration<T> {
private abstract static class AbstractNamingEnumeration<T> implements NamingEnumeration<T> {
private Iterator<T> iterator;
private final Iterator<T> iterator;
private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException {
if (!"".equals(proot) && !proot.endsWith("/")) {
if (!proot.isEmpty() && !proot.endsWith("/")) {
proot = proot + "/";
}
String root = context.root + proot;
@@ -353,7 +353,7 @@ public class SimpleNamingContext implements Context {
}
private static class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
private static final class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
@@ -366,7 +366,7 @@ public class SimpleNamingContext implements Context {
}
private static class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
private static final class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
@@ -1,3 +1,5 @@
package org.springframework.scripting.groovy;
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.scripting.ContextScriptBean
@@ -1,3 +1,5 @@
package org.springframework.scripting.groovy;
import org.springframework.beans.factory.FactoryBean
class TestFactoryBean implements FactoryBean {
@@ -1 +1,3 @@
package org.springframework.scripting.groovy;
return 3 * 2
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -503,7 +503,7 @@ public class GenericConversionService implements ConfigurableConversionService {
private final Set<GenericConverter> globalConverters = new LinkedHashSet<GenericConverter>();
private final Map<ConvertiblePair, ConvertersForPair> converters =
new LinkedHashMap<ConvertiblePair, ConvertersForPair>(36);
new LinkedHashMap<ConvertiblePair, ConvertersForPair>(256);
public void add(GenericConverter converter) {
Set<ConvertiblePair> convertibleTypes = converter.getConvertibleTypes();
@@ -514,8 +514,7 @@ public class GenericConversionService implements ConfigurableConversionService {
}
else {
for (ConvertiblePair convertiblePair : convertibleTypes) {
ConvertersForPair convertersForPair = getMatchableConverters(convertiblePair);
convertersForPair.add(converter);
getMatchableConverters(convertiblePair).add(converter);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 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.
@@ -30,9 +30,9 @@ import org.springframework.core.convert.converter.Converter;
*/
final class StringToBooleanConverter implements Converter<String, Boolean> {
private static final Set<String> trueValues = new HashSet<String>(4);
private static final Set<String> trueValues = new HashSet<String>(8);
private static final Set<String> falseValues = new HashSet<String>(4);
private static final Set<String> falseValues = new HashSet<String>(8);
static {
trueValues.add("true");
@@ -46,10 +46,11 @@ final class StringToBooleanConverter implements Converter<String, Boolean> {
falseValues.add("0");
}
@Override
public Boolean convert(String source) {
String value = source.trim();
if ("".equals(value)) {
if (value.isEmpty()) {
return null;
}
value = value.toLowerCase();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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,6 +18,7 @@ package org.springframework.core.io.support;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Properties;
@@ -180,7 +181,8 @@ public abstract class PropertiesLoaderSupport {
catch (IOException ex) {
// Resource not found when trying to open it
if (this.ignoreResourceNotFound &&
(ex instanceof FileNotFoundException || ex instanceof UnknownHostException)) {
(ex instanceof FileNotFoundException || ex instanceof UnknownHostException ||
ex instanceof SocketException)) {
if (logger.isInfoEnabled()) {
logger.info("Properties resource not found: " + ex.getMessage());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -32,6 +32,8 @@ public interface PropertySourceFactory {
/**
* Create a {@link PropertySource} that wraps the given resource.
* @param name the name of the property source
* (can be {@code null} in which case the factory implementation
* will have to generate a name based on the given resource)
* @param resource the resource (potentially encoded) to wrap
* @return the new {@link PropertySource} (never {@code null})
* @throws IOException if resource resolution failed
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -122,6 +122,11 @@ public class SimpleAsyncTaskExecutor extends CustomizableThreadCreator
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* is limited to plain {@code Runnable} execution via {@code execute} calls.
* In case of {@code #submit} calls, the exposed {@code Runnable} will be a
* {@code FutureTask} which does not propagate any exceptions; you might
* have to cast it and call {@code Future#get} to evaluate exceptions.
* @since 4.3
*/
public final void setTaskDecorator(TaskDecorator taskDecorator) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -27,16 +27,23 @@ package org.springframework.core.task;
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
*
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* may be limited. Specifically in case of a {@code Future}-based operation,
* the exposed {@code Runnable} will be a wrapper which does not propagate
* any exceptions from its {@code run} method.
*
* @author Juergen Hoeller
* @since 4.3
* @see TaskExecutor#execute(Runnable)
* @see SimpleAsyncTaskExecutor#setTaskDecorator
* @see org.springframework.core.task.support.TaskExecutorAdapter#setTaskDecorator
*/
public interface TaskDecorator {
/**
* Decorate the given {@code Runnable}, returning a potentially wrapped
* {@code Runnable} for actual execution.
* {@code Runnable} for actual execution, internally delegating to the
* original {@link Runnable#run()} implementation.
* @param runnable the original {@code Runnable}
* @return the decorated {@code Runnable}
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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,6 +68,11 @@ public class TaskExecutorAdapter implements AsyncListenableTaskExecutor {
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* is limited to plain {@code Runnable} execution via {@code execute} calls.
* In case of {@code #submit} calls, the exposed {@code Runnable} will be a
* {@code FutureTask} which does not propagate any exceptions; you might
* have to cast it and call {@code Future#get} to evaluate exceptions.
* @since 4.3
*/
public final void setTaskDecorator(TaskDecorator taskDecorator) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -206,7 +206,7 @@ public abstract class ClassUtils {
* @param name the name of the Class
* @param classLoader the class loader to use
* (may be {@code null}, which indicates the default class loader)
* @return Class instance for the supplied name
* @return a class instance for the supplied name
* @throws ClassNotFoundException if the class was not found
* @throws LinkageError if the class file could not be loaded
* @see Class#forName(String, boolean, ClassLoader)
@@ -275,7 +275,7 @@ public abstract class ClassUtils {
* @param className the name of the Class
* @param classLoader the class loader to use
* (may be {@code null}, which indicates the default class loader)
* @return Class instance for the supplied name
* @return a class instance for the supplied name
* @throws IllegalArgumentException if the class name was not resolvable
* (that is, the class could not be found or the class file could not be loaded)
* @see #forName(String, ClassLoader)
@@ -459,7 +459,7 @@ public abstract class ClassUtils {
* @param lhsType the target type
* @param rhsType the value type that should be assigned to the target type
* @return if the target type is assignable from the value type
* @see TypeUtils#isAssignable
* @see TypeUtils#isAssignable(java.lang.reflect.Type, java.lang.reflect.Type)
*/
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
Assert.notNull(lhsType, "Left-hand side type must not be null");
@@ -469,17 +469,12 @@ public abstract class ClassUtils {
}
if (lhsType.isPrimitive()) {
Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType);
if (lhsType == resolvedPrimitive) {
return true;
}
return (lhsType == resolvedPrimitive);
}
else {
Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);
if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) {
return true;
}
return (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper));
}
return false;
}
/**
@@ -990,7 +985,7 @@ public abstract class ClassUtils {
* @param clazz the clazz to analyze
* @param paramTypes the parameter types of the method
* @return whether the class has a corresponding constructor
* @see Class#getMethod
* @see Class#getConstructor
*/
public static boolean hasConstructor(Class<?> clazz, Class<?>... paramTypes) {
return (getConstructorIfAvailable(clazz, paramTypes) != null);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -418,7 +418,7 @@ public abstract class CollectionUtils {
@Override
public V getFirst(K key) {
List<V> values = this.map.get(key);
return (values != null ? values.get(0) : null);
return (values != null && !values.isEmpty() ? values.get(0) : null);
}
@Override
@@ -439,7 +439,10 @@ public abstract class CollectionUtils {
public Map<K, V> toSingleValueMap() {
LinkedHashMap<K, V> singleValueMap = new LinkedHashMap<K,V>(this.map.size());
for (Entry<K, List<V>> entry : map.entrySet()) {
singleValueMap.put(entry.getKey(), entry.getValue().get(0));
List<V> values = entry.getValue();
if (values != null && !values.isEmpty()) {
singleValueMap.put(entry.getKey(), values.get(0));
}
}
return singleValueMap;
}
@@ -506,10 +509,7 @@ public abstract class CollectionUtils {
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
return this.map.equals(other);
return (this == other || this.map.equals(other));
}
@Override
@@ -292,7 +292,7 @@ public class FastByteArrayOutputStream extends OutputStream {
}
/**
* Create a new buffer and store it in the LinkedList
* Create a new buffer and store it in the LinkedList.
* <p>Adds a new buffer that can store at least {@code minCapacity} bytes.
*/
private void addBuffer(int minCapacity) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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.
@@ -40,9 +40,13 @@ import java.io.Writer;
* @author Juergen Hoeller
* @since 06.10.2003
* @see StreamUtils
* @see FileSystemUtils
*/
public abstract class FileCopyUtils {
/**
* The default buffer size used when copying bytes.
*/
public static final int BUFFER_SIZE = StreamUtils.BUFFER_SIZE;
@@ -184,15 +188,15 @@ public abstract class FileCopyUtils {
Assert.notNull(out, "No Writer specified");
try {
int byteCount = 0;
int charCount = 0;
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
int charsRead;
while ((charsRead = in.read(buffer)) != -1) {
out.write(buffer, 0, charsRead);
charCount += charsRead;
}
out.flush();
return byteCount;
return charCount;
}
finally {
try {
@@ -209,7 +213,7 @@ public abstract class FileCopyUtils {
}
/**
* Copy the contents of the given String to the given output Writer.
* Copy the contents of the given String to the given Writer.
* Closes the writer when done.
* @param in the String to copy from
* @param out the Writer to copy to
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -216,8 +216,8 @@ public class LinkedCaseInsensitiveMap<V> implements Map<String, V>, Serializable
}
@Override
public boolean equals(Object obj) {
return this.targetMap.equals(obj);
public boolean equals(Object other) {
return (this == other || this.targetMap.equals(other));
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -208,8 +208,8 @@ public class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializa
}
@Override
public boolean equals(Object obj) {
return this.targetMap.equals(obj);
public boolean equals(Object other) {
return (this == other || this.targetMap.equals(other));
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -193,7 +193,7 @@ public class MimeType implements Comparable<MimeType>, Serializable {
* @see <a href="https://tools.ietf.org/html/rfc2616#section-2.2">HTTP 1.1, section 2.2</a>
*/
private void checkToken(String token) {
for (int i = 0; i < token.length(); i++ ) {
for (int i = 0; i < token.length(); i++) {
char ch = token.charAt(i);
if (!TOKEN.get(ch)) {
throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + token + "\"");
@@ -206,8 +206,7 @@ public class MimeType implements Comparable<MimeType>, Serializable {
Assert.hasLength(value, "'value' must not be empty");
checkToken(attribute);
if (PARAM_CHARSET.equals(attribute)) {
value = unquote(value);
Charset.forName(value);
Charset.forName(unquote(value));
}
else if (!isQuotedString(value)) {
checkToken(value);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -260,7 +260,7 @@ public abstract class MimeTypeUtils {
throw new InvalidMimeTypeException(mimeType, "does not contain subtype after '/'");
}
String type = fullType.substring(0, subIndex);
String subtype = fullType.substring(subIndex + 1, fullType.length());
String subtype = fullType.substring(subIndex + 1);
if (MimeType.WILDCARD_TYPE.equals(type) && !MimeType.WILDCARD_TYPE.equals(subtype)) {
throw new InvalidMimeTypeException(mimeType, "wildcard type is legal only in '*/*' (all mime types)");
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 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,6 +43,9 @@ import java.nio.charset.Charset;
*/
public abstract class StreamUtils {
/**
* The default buffer size used when copying bytes.
*/
public static final int BUFFER_SIZE = 4096;
private static final byte[] EMPTY_CONTENT = new byte[0];
@@ -50,7 +53,7 @@ public abstract class StreamUtils {
/**
* Copy the contents of the given InputStream into a new byte array.
* Leaves the stream open when done.
* <p>Leaves the stream open when done.
* @param in the stream to copy from (may be {@code null} or empty)
* @return the new byte array that has been copied to (possibly empty)
* @throws IOException in case of I/O errors
@@ -67,8 +70,9 @@ public abstract class StreamUtils {
/**
* Copy the contents of the given InputStream into a String.
* Leaves the stream open when done.
* <p>Leaves the stream open when done.
* @param in the InputStream to copy from (may be {@code null} or empty)
* @param charset the {@link Charset} to use to decode the bytes
* @return the String that has been copied to (possibly empty)
* @throws IOException in case of I/O errors
*/
@@ -77,19 +81,19 @@ public abstract class StreamUtils {
return "";
}
StringBuilder out = new StringBuilder();
StringBuilder out = new StringBuilder(BUFFER_SIZE);
InputStreamReader reader = new InputStreamReader(in, charset);
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, bytesRead);
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, charsRead);
}
return out.toString();
}
/**
* Copy the contents of the given byte array to the given OutputStream.
* Leaves the stream open when done.
* <p>Leaves the stream open when done.
* @param in the byte array to copy from
* @param out the OutputStream to copy to
* @throws IOException in case of I/O errors
@@ -99,11 +103,12 @@ public abstract class StreamUtils {
Assert.notNull(out, "No OutputStream specified");
out.write(in);
out.flush();
}
/**
* Copy the contents of the given String to the given output OutputStream.
* Leaves the stream open when done.
* Copy the contents of the given String to the given OutputStream.
* <p>Leaves the stream open when done.
* @param in the String to copy from
* @param charset the Charset
* @param out the OutputStream to copy to
@@ -111,7 +116,7 @@ public abstract class StreamUtils {
*/
public static void copy(String in, Charset charset, OutputStream out) throws IOException {
Assert.notNull(in, "No input String specified");
Assert.notNull(charset, "No charset specified");
Assert.notNull(charset, "No Charset specified");
Assert.notNull(out, "No OutputStream specified");
Writer writer = new OutputStreamWriter(out, charset);
@@ -121,7 +126,7 @@ public abstract class StreamUtils {
/**
* Copy the contents of the given InputStream to the given OutputStream.
* Leaves both streams open when done.
* <p>Leaves both streams open when done.
* @param in the InputStream to copy from
* @param out the OutputStream to copy to
* @return the number of bytes copied
@@ -133,7 +138,7 @@ public abstract class StreamUtils {
int byteCount = 0;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
@@ -165,7 +170,7 @@ public abstract class StreamUtils {
}
long bytesToCopy = end - start + 1;
byte[] buffer = new byte[StreamUtils.BUFFER_SIZE];
byte[] buffer = new byte[(int) Math.min(StreamUtils.BUFFER_SIZE, bytesToCopy)];
while (bytesToCopy > 0) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) {
@@ -185,7 +190,7 @@ public abstract class StreamUtils {
/**
* Drain the remaining content of the given InputStream.
* Leaves the InputStream open when done.
* <p>Leaves the InputStream open when done.
* @param in the InputStream to drain
* @return the number of bytes read
* @throws IOException in case of I/O errors
@@ -255,7 +260,7 @@ public abstract class StreamUtils {
@Override
public void write(byte[] b, int off, int let) throws IOException {
// It is critical that we override this method for performance
out.write(b, off, let);
this.out.write(b, off, let);
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -244,7 +244,7 @@ public class MethodReference extends SpelNodeImpl {
Method method = ((ReflectiveMethodExecutor) executorToCheck.get()).getMethod();
String descriptor = CodeFlow.toDescriptor(method.getReturnType());
if (this.nullSafe && CodeFlow.isPrimitive(descriptor)) {
originalPrimitiveExitTypeDescriptor = descriptor;
this.originalPrimitiveExitTypeDescriptor = descriptor;
this.exitTypeDescriptor = CodeFlow.toBoxedDescriptor(descriptor);
}
else {
@@ -296,7 +296,7 @@ public class MethodReference extends SpelNodeImpl {
return true;
}
@Override
public void generateCode(MethodVisitor mv, CodeFlow cf) {
CachedMethodExecutor executorToCheck = this.cachedExecutor;
@@ -327,7 +327,7 @@ public class MethodReference extends SpelNodeImpl {
// Something on the stack when nothing is needed
mv.visitInsn(POP);
}
if (CodeFlow.isPrimitive(descriptor)) {
CodeFlow.insertBoxIfNecessary(mv, descriptor.charAt(0));
}
@@ -340,8 +340,10 @@ public class MethodReference extends SpelNodeImpl {
}
generateCodeForArguments(mv, cf, method, this.children);
mv.visitMethodInsn((isStaticMethod ? INVOKESTATIC : INVOKEVIRTUAL), classDesc, method.getName(),
CodeFlow.createSignatureDescriptor(method), method.getDeclaringClass().isInterface());
mv.visitMethodInsn(
(isStaticMethod ? INVOKESTATIC : (isJava8DefaultMethod(method) ? INVOKEINTERFACE : INVOKEVIRTUAL)),
classDesc, method.getName(), CodeFlow.createSignatureDescriptor(method),
method.getDeclaringClass().isInterface());
cf.pushDescriptor(this.exitTypeDescriptor);
if (this.originalPrimitiveExitTypeDescriptor != null) {
@@ -354,6 +356,11 @@ public class MethodReference extends SpelNodeImpl {
}
}
private static boolean isJava8DefaultMethod(Method method) {
return (method.getDeclaringClass().isInterface() && Modifier.isPublic(method.getModifiers()) &&
!Modifier.isAbstract(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()));
}
private class MethodValueRef implements ValueRef {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -45,7 +45,7 @@ import org.springframework.util.StringUtils;
/**
* A powerful {@link PropertyAccessor} that uses reflection to access properties
* for reading and possibly also for writing.
* for reading and possibly also for writing on a target instance.
*
* <p>A property can be referenced through a public getter method (when being read)
* or a public setter method (when being written), and also as a public field.
@@ -98,8 +98,8 @@ public class ReflectivePropertyAccessor implements PropertyAccessor {
}
/**
* Create a new property accessor for reading and possibly writing.
* @param allowWrite whether to also allow for write operations
* Create a new property accessor for reading and possibly also writing.
* @param allowWrite whether to allow write operations on a target instance
* @since 4.3.15
* @see #canWrite
*/
@@ -619,8 +619,8 @@ public class ReflectivePropertyAccessor implements PropertyAccessor {
@Override
public String toString() {
return "CacheKey [clazz=" + this.clazz.getName() + ", property=" + this.property + ", " +
this.property + ", targetIsClass=" + this.targetIsClass + "]";
return "PropertyCacheKey [clazz=" + this.clazz.getName() + ", property=" + this.property +
", targetIsClass=" + this.targetIsClass + "]";
}
@Override
@@ -644,6 +644,9 @@ public class ReflectivePropertyAccessor implements PropertyAccessor {
*/
public static class OptimalPropertyAccessor implements CompilablePropertyAccessor {
/**
* The member being accessed.
*/
public final Member member;
private final TypeDescriptor typeDescriptor;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 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.
@@ -97,7 +97,7 @@ public interface JdbcOperations {
* @param rse a callback that will extract all rows of results
* @return an arbitrary result object, as returned by the ResultSetExtractor
* @throws DataAccessException if there is any problem executing the query
* @see #query(String, Object[], ResultSetExtractor)
* @see #query(String, ResultSetExtractor, Object...)
*/
<T> T query(String sql, ResultSetExtractor<T> rse) throws DataAccessException;
@@ -110,7 +110,7 @@ public interface JdbcOperations {
* @param sql the SQL query to execute
* @param rch a callback that will extract results, one row at a time
* @throws DataAccessException if there is any problem executing the query
* @see #query(String, Object[], RowCallbackHandler)
* @see #query(String, RowCallbackHandler, Object...)
*/
void query(String sql, RowCallbackHandler rch) throws DataAccessException;
@@ -124,7 +124,7 @@ public interface JdbcOperations {
* @param rowMapper a callback that will map one object per row
* @return the result List, containing mapped objects
* @throws DataAccessException if there is any problem executing the query
* @see #query(String, Object[], RowMapper)
* @see #query(String, RowMapper, Object...)
*/
<T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException;
@@ -142,7 +142,7 @@ public interface JdbcOperations {
* @throws IncorrectResultSizeDataAccessException if the query does not
* return exactly one row
* @throws DataAccessException if there is any problem executing the query
* @see #queryForObject(String, Object[], RowMapper)
* @see #queryForObject(String, RowMapper, Object...)
*/
<T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException;
@@ -161,7 +161,7 @@ public interface JdbcOperations {
* @throws IncorrectResultSizeDataAccessException if the query does not return
* exactly one row, or does not return exactly one column in that row
* @throws DataAccessException if there is any problem executing the query
* @see #queryForObject(String, Object[], Class)
* @see #queryForObject(String, Class, Object...)
*/
<T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException;
@@ -178,7 +178,7 @@ public interface JdbcOperations {
* @throws IncorrectResultSizeDataAccessException if the query does not
* return exactly one row
* @throws DataAccessException if there is any problem executing the query
* @see #queryForMap(String, Object[])
* @see #queryForMap(String, Object...)
* @see ColumnMapRowMapper
*/
Map<String, Object> queryForMap(String sql) throws DataAccessException;
@@ -195,7 +195,7 @@ public interface JdbcOperations {
* (for example, {@code Integer.class})
* @return a List of objects that match the specified element type
* @throws DataAccessException if there is any problem executing the query
* @see #queryForList(String, Object[], Class)
* @see #queryForList(String, Class, Object...)
* @see SingleColumnRowMapper
*/
<T> List<T> queryForList(String sql, Class<T> elementType) throws DataAccessException;
@@ -212,7 +212,7 @@ public interface JdbcOperations {
* @param sql the SQL query to execute
* @return an List that contains a Map per row
* @throws DataAccessException if there is any problem executing the query
* @see #queryForList(String, Object[])
* @see #queryForList(String, Object...)
*/
List<Map<String, Object>> queryForList(String sql) throws DataAccessException;
@@ -231,7 +231,7 @@ public interface JdbcOperations {
* @return a SqlRowSet representation (possibly a wrapper around a
* {@code javax.sql.rowset.CachedRowSet})
* @throws DataAccessException if there is any problem executing the query
* @see #queryForRowSet(String, Object[])
* @see #queryForRowSet(String, Object...)
* @see SqlRowSetResultSetExtractor
* @see javax.sql.rowset.CachedRowSet
*/
@@ -884,6 +884,7 @@ public interface JdbcOperations {
* @param sql the SQL statement to execute
* @param batchArgs the List of Object arrays containing the batch of arguments for the query
* @return an array containing the numbers of rows affected by each update in the batch
* @throws DataAccessException if there is any problem issuing the update
*/
int[] batchUpdate(String sql, List<Object[]> batchArgs) throws DataAccessException;
@@ -894,6 +895,7 @@ public interface JdbcOperations {
* @param argTypes the SQL types of the arguments
* (constants from {@code java.sql.Types})
* @return an array containing the numbers of rows affected by each update in the batch
* @throws DataAccessException if there is any problem issuing the update
*/
int[] batchUpdate(String sql, List<Object[]> batchArgs, int[] argTypes) throws DataAccessException;
@@ -907,6 +909,7 @@ public interface JdbcOperations {
* @param pss the ParameterizedPreparedStatementSetter to use
* @return an array containing for each batch another array containing the numbers of rows affected
* by each update in the batch
* @throws DataAccessException if there is any problem issuing the update
* @since 3.1
*/
<T> int[][] batchUpdate(String sql, Collection<T> batchArgs, int batchSize,
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -31,7 +31,6 @@ import java.util.Set;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor;
import org.springframework.util.Assert;
/**
* Helper class that efficiently creates multiple {@link PreparedStatementCreator}
@@ -201,10 +200,9 @@ public class PreparedStatementCreatorFactory {
public PreparedStatementCreatorImpl(String actualSql, List<?> parameters) {
this.actualSql = actualSql;
Assert.notNull(parameters, "Parameters List must not be null");
this.parameters = parameters;
if (this.parameters.size() != declaredParameters.size()) {
// account for named parameters being used multiple times
if (parameters.size() != declaredParameters.size()) {
// Account for named parameters being used multiple times
Set<String> names = new HashSet<String>();
for (int i = 0; i < parameters.size(); i++) {
Object param = parameters.get(i);
@@ -278,7 +276,7 @@ public class PreparedStatementCreatorFactory {
Collection<?> entries = (Collection<?>) in;
for (Object entry : entries) {
if (entry instanceof Object[]) {
Object[] valueArray = ((Object[])entry);
Object[] valueArray = ((Object[]) entry);
for (Object argValue : valueArray) {
StatementCreatorUtils.setParameterValue(psToUse, sqlColIndx++, declaredParameter, argValue);
}

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