Compare commits

..

1 Commits

Author SHA1 Message Date
Spring Builds 4343423f1c Release v5.3.15 2022-01-13 11:08:53 +00:00
340 changed files with 4520 additions and 7273 deletions
-3
View File
@@ -1,3 +0,0 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=8.0.322-librca
+29 -34
View File
@@ -2,7 +2,7 @@ plugins {
id 'io.spring.dependency-management' version '1.0.11.RELEASE' apply false
id 'io.spring.nohttp' version '0.0.10'
id "io.freefair.aspectj" version '6.2.0' apply false
id 'org.jetbrains.dokka' version '1.6.10' apply false
id 'org.jetbrains.dokka' version '1.5.0' apply false
id 'org.jetbrains.kotlin.jvm' version '1.5.32' apply false
id "org.jetbrains.kotlin.plugin.serialization" version "1.5.32" apply false
id 'org.asciidoctor.jvm.convert' version '3.3.2'
@@ -28,24 +28,24 @@ configure(allprojects) { project ->
dependencyManagement {
imports {
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.6"
mavenBom "io.netty:netty-bom:4.1.75.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.17"
mavenBom "io.r2dbc:r2dbc-bom:Arabba-SR12"
mavenBom "io.netty:netty-bom:4.1.72.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.15"
mavenBom "io.r2dbc:r2dbc-bom:Arabba-SR11"
mavenBom "io.rsocket:rsocket-bom:1.1.1"
mavenBom "org.eclipse.jetty:jetty-bom:9.4.45.v20220203"
mavenBom "org.eclipse.jetty:jetty-bom:9.4.44.v20210927"
mavenBom "org.jetbrains.kotlin:kotlin-bom:1.5.32"
mavenBom "org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.5.2"
mavenBom "org.jetbrains.kotlinx:kotlinx-serialization-bom:1.2.2"
mavenBom "org.junit:junit-bom:5.8.2"
}
dependencies {
dependencySet(group: 'org.apache.logging.log4j', version: '2.17.2') {
dependencySet(group: 'org.apache.logging.log4j', version: '2.17.1') {
entry 'log4j-api'
entry 'log4j-core'
entry 'log4j-jul'
entry 'log4j-slf4j-impl'
}
dependency "org.slf4j:slf4j-api:1.7.36"
dependency "org.slf4j:slf4j-api:1.7.32"
dependency("com.google.code.findbugs:findbugs:3.0.1") {
exclude group: "dom4j", name: "dom4j"
}
@@ -68,22 +68,22 @@ configure(allprojects) { project ->
dependency "io.reactivex:rxjava-reactive-streams:1.2.1"
dependency "io.reactivex.rxjava2:rxjava:2.2.21"
dependency "io.reactivex.rxjava3:rxjava:3.1.3"
dependency "io.smallrye.reactive:mutiny:1.4.0"
dependency "io.smallrye.reactive:mutiny:1.2.0"
dependency "io.projectreactor.tools:blockhound:1.0.6.RELEASE"
dependency "com.caucho:hessian:4.0.63"
dependency "com.fasterxml:aalto-xml:1.3.1"
dependency("com.fasterxml.woodstox:woodstox-core:6.2.8") {
dependency "com.fasterxml:aalto-xml:1.3.0"
dependency("com.fasterxml.woodstox:woodstox-core:6.2.7") {
exclude group: "stax", name: "stax-api"
}
dependency "com.google.code.gson:gson:2.8.9"
dependency "com.google.protobuf:protobuf-java-util:3.19.3"
dependency "com.google.protobuf:protobuf-java-util:3.19.1"
dependency "com.googlecode.protobuf-java-format:protobuf-java-format:1.4"
dependency("com.thoughtworks.xstream:xstream:1.4.18") {
exclude group: "xpp3", name: "xpp3_min"
exclude group: "xmlpull", name: "xmlpull"
}
dependency "org.apache.johnzon:johnzon-jsonb:1.2.16"
dependency "org.apache.johnzon:johnzon-jsonb:1.2.15"
dependency("org.codehaus.jettison:jettison:1.3.8") {
exclude group: "stax", name: "stax-api"
}
@@ -94,10 +94,10 @@ configure(allprojects) { project ->
dependency "org.ogce:xpp3:1.1.6"
dependency "org.yaml:snakeyaml:1.30"
dependency "com.h2database:h2:2.1.210"
dependency "com.h2database:h2:2.0.206"
dependency "com.github.ben-manes.caffeine:caffeine:2.9.3"
dependency "com.github.librepdf:openpdf:1.3.26"
dependency "com.rometools:rome:1.18.0"
dependency "com.rometools:rome:1.16.0"
dependency "commons-io:commons-io:2.5"
dependency "io.vavr:vavr:0.10.4"
dependency "net.sf.jopt-simple:jopt-simple:5.0.4"
@@ -124,22 +124,22 @@ configure(allprojects) { project ->
dependency "org.ehcache:jcache:1.0.1"
dependency "org.ehcache:ehcache:3.4.0"
dependency "org.hibernate:hibernate-core:5.4.33.Final"
dependency "org.hibernate:hibernate-validator:6.2.3.Final"
dependency "org.hibernate:hibernate-validator:6.2.1.Final"
dependency "org.webjars:webjars-locator-core:0.48"
dependency "org.webjars:underscorejs:1.8.3"
dependencySet(group: 'org.apache.tomcat', version: '9.0.60') {
dependencySet(group: 'org.apache.tomcat', version: '9.0.56') {
entry 'tomcat-util'
entry('tomcat-websocket') {
exclude group: "org.apache.tomcat", name: "tomcat-servlet-api"
exclude group: "org.apache.tomcat", name: "tomcat-websocket-api"
}
}
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.60') {
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.56') {
entry 'tomcat-embed-core'
entry 'tomcat-embed-websocket'
}
dependencySet(group: 'io.undertow', version: '2.2.16.Final') {
dependencySet(group: 'io.undertow', version: '2.2.14.Final') {
entry 'undertow-core'
entry('undertow-servlet') {
exclude group: "org.jboss.spec.javax.servlet", name: "jboss-servlet-api_4.0_spec"
@@ -151,8 +151,8 @@ configure(allprojects) { project ->
}
dependency "org.eclipse.jetty:jetty-reactive-httpclient:1.1.10"
dependency 'org.apache.httpcomponents.client5:httpclient5:5.1.3'
dependency 'org.apache.httpcomponents.core5:httpcore5-reactive:5.1.3'
dependency 'org.apache.httpcomponents.client5:httpclient5:5.1.2'
dependency 'org.apache.httpcomponents.core5:httpcore5-reactive:5.1.2'
dependency("org.apache.httpcomponents:httpclient:4.5.13") {
exclude group: "commons-logging", name: "commons-logging"
}
@@ -192,13 +192,13 @@ configure(allprojects) { project ->
dependency "org.hamcrest:hamcrest:2.1"
dependency "org.awaitility:awaitility:3.1.6"
dependency "org.assertj:assertj-core:3.22.0"
dependencySet(group: 'org.xmlunit', version: '2.9.0') {
dependencySet(group: 'org.xmlunit', version: '2.8.4') {
entry 'xmlunit-assertj'
entry('xmlunit-matchers') {
exclude group: "org.hamcrest", name: "hamcrest-core"
}
}
dependencySet(group: 'org.mockito', version: '4.4.0') {
dependencySet(group: 'org.mockito', version: '4.2.0') {
entry('mockito-core') {
exclude group: "org.hamcrest", name: "hamcrest-core"
}
@@ -206,10 +206,10 @@ configure(allprojects) { project ->
}
dependency "io.mockk:mockk:1.12.1"
dependency("net.sourceforge.htmlunit:htmlunit:2.59.0") {
dependency("net.sourceforge.htmlunit:htmlunit:2.56.0") {
exclude group: "commons-logging", name: "commons-logging"
}
dependency("org.seleniumhq.selenium:htmlunit-driver:2.59.0") {
dependency("org.seleniumhq.selenium:htmlunit-driver:2.56.0") {
exclude group: "commons-logging", name: "commons-logging"
}
dependency("org.seleniumhq.selenium:selenium-java:3.141.59") {
@@ -238,7 +238,7 @@ configure(allprojects) { project ->
dependency "com.ibm.websphere:uow:6.0.2.17"
dependency "com.jamonapi:jamon:2.82"
dependency "joda-time:joda-time:2.10.13"
dependency "org.eclipse.persistence:org.eclipse.persistence.jpa:2.7.10"
dependency "org.eclipse.persistence:org.eclipse.persistence.jpa:2.7.9"
dependency "org.javamoney:moneta:1.3"
dependency "com.sun.activation:javax.activation:1.2.0"
@@ -340,7 +340,7 @@ configure([rootProject] + javaProjects) { project ->
}
checkstyle {
toolVersion = "9.3"
toolVersion = "9.2"
configDirectory.set(rootProject.file("src/checkstyle"))
}
@@ -362,7 +362,7 @@ configure([rootProject] + javaProjects) { project ->
// JSR-305 only used for non-required meta-annotations
compileOnly("com.google.code.findbugs:jsr305")
testCompileOnly("com.google.code.findbugs:jsr305")
checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:0.0.31")
checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:0.0.29")
}
ext.javadocLinks = [
@@ -388,13 +388,7 @@ configure([rootProject] + javaProjects) { project ->
// "https://junit.org/junit5/docs/5.8.2/api/",
"https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/",
"https://javadoc.io/static/io.rsocket/rsocket-core/1.1.1/",
"https://r2dbc.io/spec/0.8.5.RELEASE/api/",
// The external Javadoc link for JSR 305 must come last to ensure that types from
// JSR 250 (such as @PostConstruct) are still supported. This is due to the fact
// that JSR 250 and JSR 305 both define types in javax.annotation, which results
// in a split package, and the javadoc tool does not support split packages
// across multiple external Javadoc sites.
"https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/3.0.2/"
"https://r2dbc.io/spec/0.8.5.RELEASE/api/"
] as String[]
}
@@ -405,6 +399,7 @@ configure(moduleProjects) { project ->
configure(rootProject) {
description = "Spring Framework"
apply plugin: "groovy"
apply plugin: "kotlin"
apply plugin: "io.spring.nohttp"
apply plugin: 'org.springframework.build.api-diff'
+2 -2
View File
@@ -1,4 +1,4 @@
FROM ubuntu:focal-20220302
FROM ubuntu:focal-20210827
ADD setup.sh /setup.sh
ADD get-jdk-url.sh /get-jdk-url.sh
@@ -6,6 +6,6 @@ RUN ./setup.sh java8
ENV JAVA_HOME /opt/openjdk/java8
ENV JDK11 /opt/openjdk/java11
ENV JDK17 /opt/openjdk/java17
ENV JDK16 /opt/openjdk/java16
ENV PATH $JAVA_HOME/bin:$PATH
+4 -7
View File
@@ -3,16 +3,13 @@ set -e
case "$1" in
java8)
echo "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u322-b06/OpenJDK8U-jdk_x64_linux_hotspot_8u322b06.tar.gz"
echo "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u302-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u302b08.tar.gz"
;;
java11)
echo "https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.14.1%2B1/OpenJDK11U-jdk_x64_linux_hotspot_11.0.14.1_1.tar.gz"
echo "https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.12%2B7/OpenJDK11U-jdk_x64_linux_hotspot_11.0.12_7.tar.gz"
;;
java17)
echo "https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.2%2B8/OpenJDK17U-jdk_x64_linux_hotspot_17.0.2_8.tar.gz"
;;
java18)
echo "https://github.com/adoptium/temurin18-binaries/releases/download/jdk18-2022-02-12-08-06-beta/OpenJDK18-jdk_x64_linux_hotspot_2022-02-12-08-06.tar.gz"
java16)
echo "https://github.com/adoptium/temurin16-binaries/releases/download/jdk-16.0.2%2B7/OpenJDK16U-jdk_x64_linux_hotspot_16.0.2_7.tar.gz"
;;
*)
echo $"Unknown java version"
+1 -1
View File
@@ -22,7 +22,7 @@ curl --output /opt/concourse-release-scripts.jar https://repo.spring.io/release/
mkdir -p /opt/openjdk
pushd /opt/openjdk > /dev/null
for jdk in java8 java11 java17
for jdk in java8 java11 java16
do
JDK_URL=$( /get-jdk-url.sh $jdk )
mkdir $jdk
+3
View File
@@ -1,3 +1,6 @@
email-server: "smtp.svc.pivotal.io"
email-from: "ci@spring.io"
email-to: ["spring-framework-dev@pivotal.io"]
github-repo: "https://github.com/spring-projects/spring-framework.git"
github-repo-name: "spring-projects/spring-framework"
docker-hub-organization: "springci"
+7 -7
View File
@@ -124,14 +124,14 @@ resources:
access_token: ((github-ci-status-token))
branch: ((branch))
context: jdk11-build
- name: repo-status-jdk17-build
- name: repo-status-jdk16-build
type: github-status-resource
icon: eye-check-outline
source:
repository: ((github-repo-name))
access_token: ((github-ci-status-token))
branch: ((branch))
context: jdk17-build
context: jdk16-build
- name: slack-alert
type: slack-notification
icon: slack
@@ -249,7 +249,7 @@ jobs:
<<: *slack-fail-params
- put: repo-status-jdk11-build
params: { state: "success", commit: "git-repo" }
- name: jdk17-build
- name: jdk16-build
serial: true
public: true
plan:
@@ -257,7 +257,7 @@ jobs:
- get: git-repo
- get: every-morning
trigger: true
- put: repo-status-jdk17-build
- put: repo-status-jdk16-build
params: { state: "pending", commit: "git-repo" }
- do:
- task: check-project
@@ -270,12 +270,12 @@ jobs:
<<: *build-project-task-params
on_failure:
do:
- put: repo-status-jdk17-build
- put: repo-status-jdk16-build
params: { state: "failure", commit: "git-repo" }
- put: slack-alert
params:
<<: *slack-fail-params
- put: repo-status-jdk17-build
- put: repo-status-jdk16-build
params: { state: "success", commit: "git-repo" }
- name: build-pull-requests
serial: true
@@ -458,7 +458,7 @@ jobs:
groups:
- name: "builds"
jobs: ["build", "jdk11-build", "jdk17-build"]
jobs: ["build", "jdk11-build", "jdk16-build"]
- name: "releases"
jobs: ["stage-milestone", "stage-rc", "stage-release", "promote-milestone", "promote-rc", "promote-release", "create-github-release"]
- name: "ci-images"
+1 -1
View File
@@ -1,4 +1,4 @@
version=5.3.17
version=5.3.15
org.gradle.jvmargs=-Xmx1536M
org.gradle.caching=true
org.gradle.parallel=true
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,6 +34,7 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ScopeMetadata;
import org.springframework.context.annotation.ScopeMetadataResolver;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
@@ -306,26 +307,29 @@ class ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests {
GenericWebApplicationContext context = new GenericWebApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
scanner.setIncludeAnnotationConfig(false);
scanner.setScopeMetadataResolver(definition -> {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
for (String type : annDef.getMetadata().getAnnotationTypes()) {
if (type.equals(javax.inject.Singleton.class.getName())) {
metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
break;
}
else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
metadata.setScopedProxyMode(scopedProxyMode);
break;
}
else if (type.startsWith("javax.inject")) {
metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
for (String type : annDef.getMetadata().getAnnotationTypes()) {
if (type.equals(javax.inject.Singleton.class.getName())) {
metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
break;
}
else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
metadata.setScopedProxyMode(scopedProxyMode);
break;
}
else if (type.startsWith("javax.inject")) {
metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
}
}
}
return metadata;
}
return metadata;
});
// Scan twice in order to find errors in the bean definition compatibility check.
+3 -4
View File
@@ -1,14 +1,13 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
maven { url "https://repo.spring.io/release" }
maven { url "https://repo.spring.io/plugins-release" }
}
}
plugins {
id "com.gradle.enterprise" version "3.8.1"
id "io.spring.ge.conventions" version "0.0.9"
id "com.gradle.enterprise" version "3.7.2"
id "io.spring.ge.conventions" version "0.0.7"
}
include "spring-aop"
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,7 +44,6 @@ import org.springframework.util.ReflectionUtils;
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @see org.springframework.aop.support.AopUtils
*/
public abstract class AopProxyUtils {
@@ -134,7 +133,7 @@ public abstract class AopProxyUtils {
if (targetClass.isInterface()) {
advised.setInterfaces(targetClass);
}
else if (Proxy.isProxyClass(targetClass) || isLambda(targetClass)) {
else if (Proxy.isProxyClass(targetClass)) {
advised.setInterfaces(targetClass.getInterfaces());
}
specifiedInterfaces = advised.getProxiedInterfaces();
@@ -245,18 +244,4 @@ public abstract class AopProxyUtils {
return arguments;
}
/**
* Determine if the supplied {@link Class} is a JVM-generated implementation
* class for a lambda expression or method reference.
* <p>This method makes a best-effort attempt at determining this, based on
* checks that work on modern, main stream JVMs.
* @param clazz the class to check
* @return {@code true} if the class is a lambda implementation class
* @since 5.3.16
*/
static boolean isLambda(Class<?> clazz) {
return (clazz.isSynthetic() && (clazz.getSuperclass() == Object.class) &&
(clazz.getInterfaces().length > 0) && clazz.getName().contains("$$Lambda"));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,7 +40,6 @@ import org.springframework.core.NativeDetector;
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @author Sam Brannen
* @since 12.03.2004
* @see AdvisedSupport#setOptimize
* @see AdvisedSupport#setProxyTargetClass
@@ -60,7 +59,7 @@ public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || AopProxyUtils.isLambda(targetClass)) {
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -233,8 +233,7 @@ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware {
return beanFactory.getBean(TaskExecutor.class);
}
catch (NoUniqueBeanDefinitionException ex) {
logger.debug("Could not find unique TaskExecutor bean. " +
"Continuing search for an Executor bean named 'taskExecutor'", ex);
logger.debug("Could not find unique TaskExecutor bean", ex);
try {
return beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class);
}
@@ -247,8 +246,7 @@ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware {
}
}
catch (NoSuchBeanDefinitionException ex) {
logger.debug("Could not find default TaskExecutor bean. " +
"Continuing search for an Executor bean named 'taskExecutor'", ex);
logger.debug("Could not find default TaskExecutor bean", ex);
try {
return beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class);
}
@@ -98,7 +98,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
}
@Test
void perTargetAspect() throws Exception {
void perTargetAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
@@ -130,7 +130,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
}
@Test
void multiplePerTargetAspects() throws Exception {
void multiplePerTargetAspects() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
@@ -158,7 +158,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
}
@Test
void multiplePerTargetAspectsWithOrderAnnotation() throws Exception {
void multiplePerTargetAspectsWithOrderAnnotation() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
@@ -184,7 +184,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
}
@Test
void perThisAspect() throws Exception {
void perThisAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
@@ -220,7 +220,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
}
@Test
void perTypeWithinAspect() throws Exception {
void perTypeWithinAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 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,6 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @since 2.0
* @author Rod Johnson
* @author Chris Beams
* @author Sam Brannen
@@ -55,7 +56,7 @@ class AspectMetadataTests {
assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.PERTARGET);
assertThat(am.getPerClausePointcut()).isInstanceOf(AspectJExpressionPointcut.class);
assertThat(((AspectJExpressionPointcut) am.getPerClausePointcut()).getExpression())
.isEqualTo("execution(* *.getSpouse())");
.isEqualTo("execution(* *.getSpouse())");
}
@Test
@@ -66,7 +67,7 @@ class AspectMetadataTests {
assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.PERTHIS);
assertThat(am.getPerClausePointcut()).isInstanceOf(AspectJExpressionPointcut.class);
assertThat(((AspectJExpressionPointcut) am.getPerClausePointcut()).getExpression())
.isEqualTo("execution(* *.getSpouse())");
.isEqualTo("execution(* *.getSpouse())");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.aop.config;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@@ -41,7 +40,7 @@ import static org.springframework.core.testfixture.io.ResourceTestUtils.qualifie
* @author Juergen Hoeller
* @author Chris Beams
*/
class AopNamespaceHandlerEventTests {
public class AopNamespaceHandlerEventTests {
private static final Class<?> CLASS = AopNamespaceHandlerEventTests.class;
@@ -58,24 +57,25 @@ class AopNamespaceHandlerEventTests {
@BeforeEach
void setup() {
public void setup() {
this.reader = new XmlBeanDefinitionReader(this.beanFactory);
this.reader.setEventListener(this.eventListener);
}
@Test
void pointcutEvents() {
public void testPointcutEvents() {
this.reader.loadBeanDefinitions(POINTCUT_EVENTS_CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertThat(componentDefinitions).as("Incorrect number of events fired").hasSize(1);
assertThat(componentDefinitions[0]).as("No holder with nested components").isInstanceOf(CompositeComponentDefinition.class);
assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(1);
boolean condition = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertThat(nestedComponentDefs).as("Incorrect number of inner components").hasSize(2);
assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(2);
PointcutComponentDefinition pcd = null;
for (ComponentDefinition componentDefinition : nestedComponentDefs) {
if (componentDefinition instanceof PointcutComponentDefinition) {
@@ -84,77 +84,84 @@ class AopNamespaceHandlerEventTests {
}
}
assertThat(pcd).as("PointcutComponentDefinition not found").isNotNull();
assertThat(pcd.getBeanDefinitions()).as("Incorrect number of BeanDefinitions").hasSize(1);
assertThat(pcd.getBeanDefinitions().length).as("Incorrect number of BeanDefinitions").isEqualTo(1);
}
@Test
void advisorEventsWithPointcutRef() {
public void testAdvisorEventsWithPointcutRef() {
this.reader.loadBeanDefinitions(POINTCUT_REF_CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertThat(componentDefinitions).as("Incorrect number of events fired").hasSize(2);
assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(2);
assertThat(componentDefinitions[0]).as("No holder with nested components").isInstanceOf(CompositeComponentDefinition.class);
boolean condition1 = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition1).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertThat(nestedComponentDefs).as("Incorrect number of inner components").hasSize(3);
assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(3);
AdvisorComponentDefinition acd = null;
for (ComponentDefinition componentDefinition : nestedComponentDefs) {
for (int i = 0; i < nestedComponentDefs.length; i++) {
ComponentDefinition componentDefinition = nestedComponentDefs[i];
if (componentDefinition instanceof AdvisorComponentDefinition) {
acd = (AdvisorComponentDefinition) componentDefinition;
break;
}
}
assertThat(acd).as("AdvisorComponentDefinition not found").isNotNull();
assertThat(acd.getBeanDefinitions()).hasSize(1);
assertThat(acd.getBeanReferences()).hasSize(2);
assertThat(acd.getBeanDefinitions().length).isEqualTo(1);
assertThat(acd.getBeanReferences().length).isEqualTo(2);
assertThat(componentDefinitions[1]).as("No advice bean found").isInstanceOf(BeanComponentDefinition.class);
boolean condition = componentDefinitions[1] instanceof BeanComponentDefinition;
assertThat(condition).as("No advice bean found").isTrue();
BeanComponentDefinition adviceDef = (BeanComponentDefinition) componentDefinitions[1];
assertThat(adviceDef.getBeanName()).isEqualTo("countingAdvice");
}
@Test
void advisorEventsWithDirectPointcut() {
public void testAdvisorEventsWithDirectPointcut() {
this.reader.loadBeanDefinitions(DIRECT_POINTCUT_EVENTS_CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertThat(componentDefinitions).as("Incorrect number of events fired").hasSize(2);
assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(2);
assertThat(componentDefinitions[0]).as("No holder with nested components").isInstanceOf(CompositeComponentDefinition.class);
boolean condition1 = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition1).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertThat(nestedComponentDefs).as("Incorrect number of inner components").hasSize(2);
assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(2);
AdvisorComponentDefinition acd = null;
for (ComponentDefinition componentDefinition : nestedComponentDefs) {
for (int i = 0; i < nestedComponentDefs.length; i++) {
ComponentDefinition componentDefinition = nestedComponentDefs[i];
if (componentDefinition instanceof AdvisorComponentDefinition) {
acd = (AdvisorComponentDefinition) componentDefinition;
break;
}
}
assertThat(acd).as("AdvisorComponentDefinition not found").isNotNull();
assertThat(acd.getBeanDefinitions()).hasSize(2);
assertThat(acd.getBeanReferences()).hasSize(1);
assertThat(acd.getBeanDefinitions().length).isEqualTo(2);
assertThat(acd.getBeanReferences().length).isEqualTo(1);
assertThat(componentDefinitions[1]).as("No advice bean found").isInstanceOf(BeanComponentDefinition.class);
boolean condition = componentDefinitions[1] instanceof BeanComponentDefinition;
assertThat(condition).as("No advice bean found").isTrue();
BeanComponentDefinition adviceDef = (BeanComponentDefinition) componentDefinitions[1];
assertThat(adviceDef.getBeanName()).isEqualTo("countingAdvice");
}
@Test
void aspectEvent() {
public void testAspectEvent() {
this.reader.loadBeanDefinitions(CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertThat(componentDefinitions).as("Incorrect number of events fired").hasSize(2);
assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(5);
assertThat(componentDefinitions[0]).as("No holder with nested components").isInstanceOf(CompositeComponentDefinition.class);
boolean condition = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertThat(nestedComponentDefs).as("Incorrect number of inner components").hasSize(2);
assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(2);
AspectComponentDefinition acd = null;
for (ComponentDefinition componentDefinition : nestedComponentDefs) {
if (componentDefinition instanceof AspectComponentDefinition) {
@@ -165,9 +172,9 @@ class AopNamespaceHandlerEventTests {
assertThat(acd).as("AspectComponentDefinition not found").isNotNull();
BeanDefinition[] beanDefinitions = acd.getBeanDefinitions();
assertThat(beanDefinitions).hasSize(5);
assertThat(beanDefinitions.length).isEqualTo(5);
BeanReference[] beanReferences = acd.getBeanReferences();
assertThat(beanReferences).hasSize(6);
assertThat(beanReferences.length).isEqualTo(6);
Set<String> expectedReferences = new HashSet<>();
expectedReferences.add("pc");
@@ -175,16 +182,19 @@ class AopNamespaceHandlerEventTests {
for (BeanReference beanReference : beanReferences) {
expectedReferences.remove(beanReference.getBeanName());
}
assertThat(expectedReferences).as("Incorrect references found").isEmpty();
assertThat(expectedReferences.size()).as("Incorrect references found").isEqualTo(0);
Arrays.stream(componentDefinitions).skip(1).forEach(definition ->
assertThat(definition).isInstanceOf(BeanComponentDefinition.class));
for (int i = 1; i < componentDefinitions.length; i++) {
boolean condition1 = componentDefinitions[i] instanceof BeanComponentDefinition;
assertThat(condition1).isTrue();
}
ComponentDefinition[] nestedComponentDefs2 = acd.getNestedComponents();
assertThat(nestedComponentDefs2).as("Inner PointcutComponentDefinition not found").hasSize(1);
assertThat(nestedComponentDefs2[0]).isInstanceOf(PointcutComponentDefinition.class);
assertThat(nestedComponentDefs2.length).as("Inner PointcutComponentDefinition not found").isEqualTo(1);
boolean condition1 = nestedComponentDefs2[0] instanceof PointcutComponentDefinition;
assertThat(condition1).isTrue();
PointcutComponentDefinition pcd = (PointcutComponentDefinition) nestedComponentDefs2[0];
assertThat(pcd.getBeanDefinitions()).as("Incorrect number of BeanDefinitions").hasSize(1);
assertThat(pcd.getBeanDefinitions().length).as("Incorrect number of BeanDefinitions").isEqualTo(1);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,10 +30,10 @@ import static org.springframework.core.testfixture.io.ResourceTestUtils.qualifie
* @author Mark Fisher
* @author Chris Beams
*/
class AopNamespaceHandlerPointcutErrorTests {
public class AopNamespaceHandlerPointcutErrorTests {
@Test
void duplicatePointcutConfig() {
public void testDuplicatePointcutConfig() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
@@ -42,7 +42,7 @@ class AopNamespaceHandlerPointcutErrorTests {
}
@Test
void missingPointcutConfig() {
public void testMissingPointcutConfig() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,10 +30,10 @@ import static org.springframework.core.testfixture.io.ResourceTestUtils.qualifie
* @author Rob Harrop
* @author Chris Beams
*/
class TopLevelAopTagTests {
public class TopLevelAopTagTests {
@Test
void parse() {
public void testParse() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(
qualifiedResource(TopLevelAopTagTests.class, "context.xml"));
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.aop.framework;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
@@ -33,7 +32,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
/**
* @author Rod Johnson
* @author Chris Beams
* @author Sam Brannen
*/
public class AopProxyUtilsTests {
@@ -134,61 +132,4 @@ public class AopProxyUtilsTests {
AopProxyUtils.proxiedUserInterfaces(proxy));
}
@Test
void isLambda() {
assertIsLambda(AopProxyUtilsTests.staticLambdaExpression);
assertIsLambda(AopProxyUtilsTests::staticStringFactory);
assertIsLambda(this.instanceLambdaExpression);
assertIsLambda(this::instanceStringFactory);
}
@Test
void isNotLambda() {
assertIsNotLambda(new EnigmaSupplier());
assertIsNotLambda(new Supplier<String>() {
@Override
public String get() {
return "anonymous inner class";
}
});
assertIsNotLambda(new Fake$$LambdaSupplier());
}
private static void assertIsLambda(Supplier<String> supplier) {
assertThat(AopProxyUtils.isLambda(supplier.getClass())).isTrue();
}
private static void assertIsNotLambda(Supplier<String> supplier) {
assertThat(AopProxyUtils.isLambda(supplier.getClass())).isFalse();
}
private static final Supplier<String> staticLambdaExpression = () -> "static lambda expression";
private final Supplier<String> instanceLambdaExpression = () -> "instance lambda expressions";
private static String staticStringFactory() {
return "static string factory";
}
private String instanceStringFactory() {
return "instance string factory";
}
private static class EnigmaSupplier implements Supplier<String> {
@Override
public String get() {
return "enigma";
}
}
private static class Fake$$LambdaSupplier implements Supplier<String> {
@Override
public String get() {
return "fake lambda";
}
}
}
@@ -125,7 +125,16 @@ public class ConcurrencyThrottleInterceptorTests {
try {
this.proxy.exceptional(this.ex);
}
catch (RuntimeException | Error err) {
catch (RuntimeException ex) {
if (ex == this.ex) {
logger.debug("Expected exception thrown", ex);
}
else {
// should never happen
ex.printStackTrace();
}
}
catch (Error err) {
if (err == this.ex) {
logger.debug("Expected exception thrown", err);
}
@@ -16,6 +16,12 @@
</aop:aspect>
</aop:config>
<bean id="getNameCounter" class="org.springframework.aop.testfixture.advice.CountingBeforeAdvice"/>
<bean id="getAgeCounter" class="org.springframework.aop.testfixture.advice.CountingBeforeAdvice"/>
<bean id="testBean" class="org.springframework.beans.testfixture.beans.TestBean"/>
<bean id="countingAdvice" class="org.springframework.aop.config.CountingAspectJAdvice"/>
</beans>
@@ -12,6 +12,10 @@
</aop:aspect>
</aop:config>
<bean id="getAgeCounter" class="org.springframework.aop.testfixture.advice.CountingBeforeAdvice"/>
<bean id="testBean" class="org.springframework.beans.testfixture.beans.TestBean"/>
<bean id="countingAdvice" class="org.springframework.aop.config.CountingAspectJAdvice"/>
</beans>
@@ -12,6 +12,10 @@
</aop:aspect>
</aop:config>
<bean id="getAgeCounter" class="org.springframework.aop.testfixture.advice.CountingBeforeAdvice"/>
<bean id="testBean" class="org.springframework.beans.testfixture.beans.TestBean"/>
<bean id="countingAdvice" class="org.springframework.aop.config.CountingAspectJAdvice"/>
</beans>
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -691,25 +691,7 @@ public abstract class BeanUtils {
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full {@link BeanWrapper}.
* <p>As of Spring Framework 5.3, this method honors generic type information
* when matching properties in the source and target objects.
* <p>The following table provides a non-exhaustive set of examples of source
* and target property types that can be copied as well as source and target
* property types that cannot be copied.
* <table border="1">
* <tr><th>source property type</th><th>target property type</th><th>copy supported</th></tr>
* <tr><td>{@code Integer}</td><td>{@code Integer}</td><td>yes</td></tr>
* <tr><td>{@code Integer}</td><td>{@code Number}</td><td>yes</td></tr>
* <tr><td>{@code List<Integer>}</td><td>{@code List<Integer>}</td><td>yes</td></tr>
* <tr><td>{@code List<?>}</td><td>{@code List<?>}</td><td>yes</td></tr>
* <tr><td>{@code List<Integer>}</td><td>{@code List<?>}</td><td>yes</td></tr>
* <tr><td>{@code List<Integer>}</td><td>{@code List<? extends Number>}</td><td>yes</td></tr>
* <tr><td>{@code String}</td><td>{@code Integer}</td><td>no</td></tr>
* <tr><td>{@code Number}</td><td>{@code Integer}</td><td>no</td></tr>
* <tr><td>{@code List<Integer>}</td><td>{@code List<Long>}</td><td>no</td></tr>
* <tr><td>{@code List<Integer>}</td><td>{@code List<Number>}</td><td>no</td></tr>
* </table>
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @throws BeansException if the copying failed
@@ -726,10 +708,7 @@ public abstract class BeanUtils {
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full {@link BeanWrapper}.
* <p>As of Spring Framework 5.3, this method honors generic type information
* when matching properties in the source and target objects. See the
* documentation for {@link #copyProperties(Object, Object)} for details.
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @param editable the class (or interface) to restrict property setting to
@@ -747,10 +726,7 @@ public abstract class BeanUtils {
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full {@link BeanWrapper}.
* <p>As of Spring Framework 5.3, this method honors generic type information
* when matching properties in the source and target objects. See the
* documentation for {@link #copyProperties(Object, Object)} for details.
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @param ignoreProperties array of property names to ignore
@@ -767,8 +743,7 @@ public abstract class BeanUtils {
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>As of Spring Framework 5.3, this method honors generic type information
* when matching properties in the source and target objects. See the
* documentation for {@link #copyProperties(Object, Object)} for details.
* when matching properties in the source and target objects.
* @param source the source bean
* @param target the target bean
* @param editable the class (or interface) to restrict property setting to
@@ -537,10 +537,10 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
* @param ann the Autowired annotation
* @return whether the annotation indicates that a dependency is required
*/
@SuppressWarnings("deprecation")
@SuppressWarnings({"deprecation", "cast"})
protected boolean determineRequiredStatus(MergedAnnotation<?> ann) {
return determineRequiredStatus(ann.<AnnotationAttributes> asMap(
mergedAnnotation -> new AnnotationAttributes(mergedAnnotation.getType())));
return determineRequiredStatus(
ann.asMap(mergedAnnotation -> new AnnotationAttributes(mergedAnnotation.getType())));
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -302,7 +302,7 @@ public class InitDestroyAnnotationBeanPostProcessor
beanDefinition.registerExternallyManagedInitMethod(methodIdentifier);
checkedInitMethods.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered init method on class [" + this.targetClass.getName() + "]: " + methodIdentifier);
logger.trace("Registered init method on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
@@ -313,7 +313,7 @@ public class InitDestroyAnnotationBeanPostProcessor
beanDefinition.registerExternallyManagedDestroyMethod(methodIdentifier);
checkedDestroyMethods.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered destroy method on class [" + this.targetClass.getName() + "]: " + methodIdentifier);
logger.trace("Registered destroy method on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -1844,7 +1844,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
@@ -1868,7 +1868,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
@@ -1908,7 +1908,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
if (logger.isTraceEnabled()) {
logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
}
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod, bean.getClass());
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -52,7 +52,6 @@ import org.springframework.util.StringUtils;
* @author Juergen Hoeller
* @author Costin Leau
* @author Stephane Nicoll
* @author Sam Brannen
* @since 2.0
* @see AbstractBeanFactory
* @see org.springframework.beans.factory.DisposableBean
@@ -110,12 +109,12 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
this.beanName = beanName;
this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
this.invokeDisposableBean = (bean instanceof DisposableBean &&
!beanDefinition.hasAnyExternallyManagedDestroyMethod(DESTROY_METHOD_NAME));
!beanDefinition.isExternallyManagedDestroyMethod(DESTROY_METHOD_NAME));
String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
if (destroyMethodName != null &&
!(this.invokeDisposableBean && DESTROY_METHOD_NAME.equals(destroyMethodName)) &&
!beanDefinition.hasAnyExternallyManagedDestroyMethod(destroyMethodName)) {
!beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
this.invokeAutoCloseable = (bean instanceof AutoCloseable && CLOSE_METHOD_NAME.equals(destroyMethodName));
if (!this.invokeAutoCloseable) {
@@ -139,7 +138,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
beanName + "' has a non-boolean parameter - not supported as destroy method");
}
}
destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod, bean.getClass());
destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod);
}
this.destroyMethod = destroyMethod;
}
@@ -253,9 +252,9 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
invokeCustomDestroyMethod(this.destroyMethod);
}
else if (this.destroyMethodName != null) {
Method destroyMethod = determineDestroyMethod(this.destroyMethodName);
if (destroyMethod != null) {
invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(destroyMethod, this.bean.getClass()));
Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
if (methodToInvoke != null) {
invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.beans.factory.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.BeanMetadataElement;
@@ -54,20 +53,6 @@ public class ManagedList<E> extends ArrayList<E> implements Mergeable, BeanMetad
}
/**
* Return a new instance containing an arbitrary number of elements.
* @param elements the elements to be contained in the list
* @param <E> the {@code List}'s element type
* @return a {@code List} containing the specified elements
* @since 5.3.16
*/
@SuppressWarnings("unchecked")
public static <E> ManagedList<E> of(E... elements) {
ManagedList<E> list = new ManagedList<>();
list.addAll(Arrays.asList(elements));
return list;
}
/**
* Set the configuration source {@code Object} for this metadata element.
* <p>The exact type of the object will depend on the configuration mechanism used.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.beans.factory.support;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.Mergeable;
@@ -57,26 +56,6 @@ public class ManagedMap<K, V> extends LinkedHashMap<K, V> implements Mergeable,
}
/**
* Return a new instance containing keys and values extracted from the
* given entries. The entries themselves are not stored in the map.
* @param entries {@code Map.Entry}s containing the keys and values
* from which the map is populated
* @param <K> the {@code Map}'s key type
* @param <V> the {@code Map}'s value type
* @return a {@code Map} containing the specified mappings
* @since 5.3.16
*/
@SafeVarargs
@SuppressWarnings("unchecked")
public static <K,V> ManagedMap<K,V> ofEntries(Entry<? extends K, ? extends V>... entries) {
ManagedMap<K,V > map = new ManagedMap<>();
for (Entry<? extends K, ? extends V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
/**
* Set the configuration source {@code Object} for this metadata element.
* <p>The exact type of the object will depend on the configuration mechanism used.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.beans.factory.support;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -53,20 +52,6 @@ public class ManagedSet<E> extends LinkedHashSet<E> implements Mergeable, BeanMe
}
/**
* Return a new instance containing an arbitrary number of elements.
* @param elements the elements to be contained in the set
* @param <E> the {@code Set}'s element type
* @return a {@code Set} containing the specified elements
* @since 5.3.16
*/
@SuppressWarnings("unchecked")
public static <E> ManagedSet<E> of(E... elements) {
ManagedSet<E> set = new ManagedSet<>();
set.addAll(Arrays.asList(elements));
return set;
}
/**
* Set the configuration source {@code Object} for this metadata element.
* <p>The exact type of the object will depend on the configuration mechanism used.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,7 +49,6 @@ import org.springframework.util.Assert;
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @see GenericBeanDefinition
* @see ChildBeanDefinition
*/
@@ -437,7 +436,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Determine if the given method or field is an externally managed configuration member.
* Check whether the given method or field is an externally managed configuration member.
*/
public boolean isExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
@@ -447,7 +446,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Get all externally managed configuration methods and fields (as an immutable Set).
* Return all externally managed configuration methods and fields (as an immutable Set).
* @since 5.3.11
*/
public Set<Member> getExternallyManagedConfigMembers() {
@@ -459,15 +458,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Register an externally managed configuration initialization method &mdash;
* for example, a method annotated with JSR-250's
* {@link javax.annotation.PostConstruct} annotation.
* <p>The supplied {@code initMethod} may be the
* {@linkplain Method#getName() simple method name} for non-private methods or the
* {@linkplain org.springframework.util.ClassUtils#getQualifiedMethodName(Method)
* qualified method name} for {@code private} methods. A qualified name is
* necessary for {@code private} methods in order to disambiguate between
* multiple private methods with the same name within a class hierarchy.
* Register an externally managed configuration initialization method.
*/
public void registerExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
@@ -479,10 +470,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Determine if the given method name indicates an externally managed
* initialization method.
* <p>See {@link #registerExternallyManagedInitMethod} for details
* regarding the format for the supplied {@code initMethod}.
* Check whether the given method name indicates an externally managed initialization method.
*/
public boolean isExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
@@ -491,40 +479,8 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
}
/**
* Determine if the given method name indicates an externally managed
* initialization method, regardless of method visibility.
* <p>In contrast to {@link #isExternallyManagedInitMethod(String)}, this
* method also returns {@code true} if there is a {@code private} externally
* managed initialization method that has been
* {@linkplain #registerExternallyManagedInitMethod(String) registered}
* using a qualified method name instead of a simple method name.
* @since 5.3.17
*/
boolean hasAnyExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (isExternallyManagedInitMethod(initMethod)) {
return true;
}
if (this.externallyManagedInitMethods != null) {
for (String candidate : this.externallyManagedInitMethods) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot >= 0) {
String methodName = candidate.substring(indexOfDot + 1);
if (methodName.equals(initMethod)) {
return true;
}
}
}
}
return false;
}
}
/**
* Return all externally managed initialization methods (as an immutable Set).
* <p>See {@link #registerExternallyManagedInitMethod} for details
* regarding the format for the initialization methods in the returned set.
* @since 5.3.11
*/
public Set<String> getExternallyManagedInitMethods() {
@@ -536,15 +492,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Register an externally managed configuration destruction method &mdash;
* for example, a method annotated with JSR-250's
* {@link javax.annotation.PreDestroy} annotation.
* <p>The supplied {@code destroyMethod} may be the
* {@linkplain Method#getName() simple method name} for non-private methods or the
* {@linkplain org.springframework.util.ClassUtils#getQualifiedMethodName(Method)
* qualified method name} for {@code private} methods. A qualified name is
* necessary for {@code private} methods in order to disambiguate between
* multiple private methods with the same name within a class hierarchy.
* Register an externally managed configuration destruction method.
*/
public void registerExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
@@ -556,10 +504,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Determine if the given method name indicates an externally managed
* destruction method.
* <p>See {@link #registerExternallyManagedDestroyMethod} for details
* regarding the format for the supplied {@code destroyMethod}.
* Check whether the given method name indicates an externally managed destruction method.
*/
public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
@@ -569,39 +514,7 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
/**
* Determine if the given method name indicates an externally managed
* destruction method, regardless of method visibility.
* <p>In contrast to {@link #isExternallyManagedDestroyMethod(String)}, this
* method also returns {@code true} if there is a {@code private} externally
* managed destruction method that has been
* {@linkplain #registerExternallyManagedDestroyMethod(String) registered}
* using a qualified method name instead of a simple method name.
* @since 5.3.17
*/
boolean hasAnyExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
if (isExternallyManagedDestroyMethod(destroyMethod)) {
return true;
}
if (this.externallyManagedDestroyMethods != null) {
for (String candidate : this.externallyManagedDestroyMethods) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot >= 0) {
String methodName = candidate.substring(indexOfDot + 1);
if (methodName.equals(destroyMethod)) {
return true;
}
}
}
}
return false;
}
}
/**
* Get all externally managed destruction methods (as an immutable Set).
* <p>See {@link #registerExternallyManagedDestroyMethod} for details
* regarding the format for the destruction methods in the returned set.
* Return all externally managed destruction methods (as an immutable Set).
* @since 5.3.11
*/
public Set<String> getExternallyManagedDestroyMethods() {
@@ -64,6 +64,6 @@ inline fun <reified T : Annotation> ListableBeanFactory.getBeansWithAnnotation()
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Annotation> ListableBeanFactory.findAnnotationOnBean(beanName:String): T? =
inline fun <reified T : Annotation> ListableBeanFactory.findAnnotationOnBean(beanName:String): Annotation? =
findAnnotationOnBean(beanName, T::class.java)
@@ -43,13 +43,13 @@ public abstract class AbstractPropertyValuesTests {
m.put("forname", "Tony");
m.put("surname", "Blair");
m.put("age", "50");
for (PropertyValue element : ps) {
Object val = m.get(element.getName());
for (int i = 0; i < ps.length; i++) {
Object val = m.get(ps[i].getName());
assertThat(val != null).as("Can't have unexpected value").isTrue();
boolean condition = val instanceof String;
assertThat(condition).as("Val i string").isTrue();
assertThat(val.equals(element.getValue())).as("val matches expected").isTrue();
m.remove(element.getName());
assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue();
m.remove(ps[i].getName());
}
assertThat(m.size() == 0).as("Map size is 0").isTrue();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -203,25 +203,8 @@ class BeanUtilsTests {
assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue();
}
/**
* {@code Integer} can be copied to {@code Number}.
*/
@Test
void copyPropertiesFromSubTypeToSuperType() {
IntegerHolder integerHolder = new IntegerHolder();
integerHolder.setNumber(42);
NumberHolder numberHolder = new NumberHolder();
BeanUtils.copyProperties(integerHolder, numberHolder);
assertThat(integerHolder.getNumber()).isEqualTo(42);
assertThat(numberHolder.getNumber()).isEqualTo(42);
}
/**
* {@code List<Integer>} can be copied to {@code List<Integer>}.
*/
@Test
void copyPropertiesHonorsGenericTypeMatchesFromIntegerToInteger() {
void copyPropertiesHonorsGenericTypeMatches() {
IntegerListHolder1 integerListHolder1 = new IntegerListHolder1();
integerListHolder1.getList().add(42);
IntegerListHolder2 integerListHolder2 = new IntegerListHolder2();
@@ -231,68 +214,6 @@ class BeanUtilsTests {
assertThat(integerListHolder2.getList()).containsOnly(42);
}
/**
* {@code List<?>} can be copied to {@code List<?>}.
*/
@Test
void copyPropertiesHonorsGenericTypeMatchesFromWildcardToWildcard() {
List<?> list = Arrays.asList("foo", 42);
WildcardListHolder1 wildcardListHolder1 = new WildcardListHolder1();
wildcardListHolder1.setList(list);
WildcardListHolder2 wildcardListHolder2 = new WildcardListHolder2();
assertThat(wildcardListHolder2.getList()).isEmpty();
BeanUtils.copyProperties(wildcardListHolder1, wildcardListHolder2);
assertThat(wildcardListHolder1.getList()).isEqualTo(list);
assertThat(wildcardListHolder2.getList()).isEqualTo(list);
}
/**
* {@code List<Integer>} can be copied to {@code List<?>}.
*/
@Test
void copyPropertiesHonorsGenericTypeMatchesFromIntegerToWildcard() {
IntegerListHolder1 integerListHolder1 = new IntegerListHolder1();
integerListHolder1.getList().add(42);
WildcardListHolder2 wildcardListHolder2 = new WildcardListHolder2();
BeanUtils.copyProperties(integerListHolder1, wildcardListHolder2);
assertThat(integerListHolder1.getList()).containsOnly(42);
assertThat(wildcardListHolder2.getList()).isEqualTo(Arrays.asList(42));
}
/**
* {@code List<Integer>} can be copied to {@code List<? extends Number>}.
*/
@Test
void copyPropertiesHonorsGenericTypeMatchesForUpperBoundedWildcard() {
IntegerListHolder1 integerListHolder1 = new IntegerListHolder1();
integerListHolder1.getList().add(42);
NumberUpperBoundedWildcardListHolder numberListHolder = new NumberUpperBoundedWildcardListHolder();
BeanUtils.copyProperties(integerListHolder1, numberListHolder);
assertThat(integerListHolder1.getList()).containsOnly(42);
assertThat(numberListHolder.getList()).hasSize(1);
assertThat(numberListHolder.getList().contains(Integer.valueOf(42))).isTrue();
}
/**
* {@code Number} can NOT be copied to {@code Integer}.
*/
@Test
void copyPropertiesDoesNotCopyeFromSuperTypeToSubType() {
NumberHolder numberHolder = new NumberHolder();
numberHolder.setNumber(Integer.valueOf(42));
IntegerHolder integerHolder = new IntegerHolder();
BeanUtils.copyProperties(numberHolder, integerHolder);
assertThat(numberHolder.getNumber()).isEqualTo(42);
assertThat(integerHolder.getNumber()).isNull();
}
/**
* {@code List<Integer>} can NOT be copied to {@code List<Long>}.
*/
@Test
void copyPropertiesDoesNotHonorGenericTypeMismatches() {
IntegerListHolder1 integerListHolder = new IntegerListHolder1();
@@ -304,20 +225,6 @@ class BeanUtilsTests {
assertThat(longListHolder.getList()).isEmpty();
}
/**
* {@code List<Integer>} can NOT be copied to {@code List<Number>}.
*/
@Test
void copyPropertiesDoesNotHonorGenericTypeMismatchesFromSubTypeToSuperType() {
IntegerListHolder1 integerListHolder = new IntegerListHolder1();
integerListHolder.getList().add(42);
NumberListHolder numberListHolder = new NumberListHolder();
BeanUtils.copyProperties(integerListHolder, numberListHolder);
assertThat(integerListHolder.getList()).containsOnly(42);
assertThat(numberListHolder.getList()).isEmpty();
}
@Test // gh-26531
void copyPropertiesIgnoresGenericsIfSourceOrTargetHasUnresolvableGenerics() throws Exception {
Order original = new Order("test", Arrays.asList("foo", "bar"));
@@ -506,90 +413,6 @@ class BeanUtilsTests {
}
@SuppressWarnings("unused")
private static class NumberHolder {
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number number) {
this.number = number;
}
}
@SuppressWarnings("unused")
private static class IntegerHolder {
private Integer number;
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
@SuppressWarnings("unused")
private static class WildcardListHolder1 {
private List<?> list = new ArrayList<>();
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
@SuppressWarnings("unused")
private static class WildcardListHolder2 {
private List<?> list = new ArrayList<>();
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
@SuppressWarnings("unused")
private static class NumberUpperBoundedWildcardListHolder {
private List<? extends Number> list = new ArrayList<>();
public List<? extends Number> getList() {
return list;
}
public void setList(List<? extends Number> list) {
this.list = list;
}
}
@SuppressWarnings("unused")
private static class NumberListHolder {
private List<Number> list = new ArrayList<>();
public List<Number> getList() {
return list;
}
public void setList(List<Number> list) {
this.list = list;
}
}
@SuppressWarnings("unused")
private static class IntegerListHolder1 {
@@ -483,7 +483,6 @@ public class BeanFactoryUtilsTests {
return TestBean.class;
}
@Override
public TestBean getObject() {
// We don't really care if the actual instance is a singleton or prototype
// for the tests that use this factory.
@@ -48,6 +48,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.TypeMismatchException;
@@ -82,6 +84,7 @@ import org.springframework.beans.testfixture.beans.factory.DummyFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.core.io.Resource;
@@ -987,13 +990,16 @@ class DefaultListableBeanFactoryTests {
@Test
void customConverter() {
GenericConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(String.class, Float.class, source -> {
try {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
return nf.parse(source).floatValue();
}
catch (ParseException ex) {
throw new IllegalArgumentException(ex);
conversionService.addConverter(new Converter<String, Float>() {
@Override
public Float convert(String source) {
try {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
return nf.parse(source).floatValue();
}
catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
});
lbf.setConversionService(conversionService);
@@ -1008,9 +1014,12 @@ class DefaultListableBeanFactoryTests {
@Test
void customEditorWithBeanReference() {
lbf.addPropertyEditorRegistrar(registry -> {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
}
});
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("myFloat", new RuntimeBeanReference("myFloat"));
@@ -2298,7 +2307,9 @@ class DefaultListableBeanFactoryTests {
@Test
void prototypeWithArrayConversionForConstructor() {
List<String> list = ManagedList.of("myName", "myBeanName");
List<String> list = new ManagedList<>();
list.add("myName");
list.add("myBeanName");
RootBeanDefinition bd = new RootBeanDefinition(DerivedTestBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.getConstructorArgumentValues().addGenericArgumentValue(list);
@@ -2314,7 +2325,9 @@ class DefaultListableBeanFactoryTests {
@Test
void prototypeWithArrayConversionForFactoryMethod() {
List<String> list = ManagedList.of("myName", "myBeanName");
List<String> list = new ManagedList<>();
list.add("myName");
list.add("myBeanName");
RootBeanDefinition bd = new RootBeanDefinition(DerivedTestBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bd.setFactoryMethodName("create");
@@ -2705,12 +2718,8 @@ class DefaultListableBeanFactoryTests {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConstructorDependency that = (ConstructorDependency) o;
return spouseAge == that.spouseAge &&
Objects.equals(spouse, that.spouse) &&
@@ -22,6 +22,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
@@ -3659,8 +3660,11 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@SuppressWarnings("unchecked")
public <T> T createMock(Class<T> toMock) {
return (T) Proxy.newProxyInstance(AutowiredAnnotationBeanPostProcessorTests.class.getClassLoader(), new Class<?>[] {toMock},
(InvocationHandler) (proxy, method, args) -> {
throw new UnsupportedOperationException("mocked!");
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
throw new UnsupportedOperationException("mocked!");
}
});
}
}
@@ -29,6 +29,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.propertyeditors.CustomDateEditor;
@@ -49,7 +50,12 @@ public class CustomEditorConfigurerTests {
CustomEditorConfigurer cec = new CustomEditorConfigurer();
final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
cec.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
registry -> registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true))});
new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
}
}});
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -113,7 +113,7 @@ public class MethodInvokingFactoryBeanTests {
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello");
mcfb.afterPropertiesSet();
mcfb.getObjectType();
@@ -184,7 +184,7 @@ public class MethodInvokingFactoryBeanTests {
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello");
// should pass
mcfb.afterPropertiesSet();
}
@@ -194,7 +194,7 @@ public class MethodInvokingFactoryBeanTests {
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method with wrong number of args").isThrownBy(
mcfb::afterPropertiesSet);
@@ -210,14 +210,14 @@ public class MethodInvokingFactoryBeanTests {
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
mcfb.afterPropertiesSet();
assertThat(mcfb.getObject()).isEqualTo("hello");
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), new Object());
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), new Object());
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method when shouldn't have matched").isThrownBy(
mcfb::afterPropertiesSet);
@@ -16,7 +16,6 @@
package org.springframework.beans.factory.config;
import java.util.AbstractMap.SimpleEntry;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -358,18 +357,22 @@ public class PropertyResourceConfigurerTests {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("stringArray", new String[] {"${os.name}", "${age}"});
List<Object> friends = ManagedList.of("na${age}me", new RuntimeBeanReference("${ref}"));
List<Object> friends = new ManagedList<>();
friends.add("na${age}me");
friends.add(new RuntimeBeanReference("${ref}"));
pvs.add("friends", friends);
Set<Object> someSet = ManagedSet.of("na${age}me",
new RuntimeBeanReference("${ref}"), new TypedStringValue("${age}", Integer.class));
Set<Object> someSet = new ManagedSet<>();
someSet.add("na${age}me");
someSet.add(new RuntimeBeanReference("${ref}"));
someSet.add(new TypedStringValue("${age}", Integer.class));
pvs.add("someSet", someSet);
Map<Object, Object> someMap = ManagedMap.ofEntries(
new SimpleEntry<>(new TypedStringValue("key${age}"), new TypedStringValue("${age}")),
new SimpleEntry<>(new TypedStringValue("key${age}ref"), new RuntimeBeanReference("${ref}")),
new SimpleEntry<>("key1", new RuntimeBeanReference("${ref}")),
new SimpleEntry<>("key2", "${age}name"));
Map<Object, Object> someMap = new ManagedMap<>();
someMap.put(new TypedStringValue("key${age}"), new TypedStringValue("${age}"));
someMap.put(new TypedStringValue("key${age}ref"), new RuntimeBeanReference("${ref}"));
someMap.put("key1", new RuntimeBeanReference("${ref}"));
someMap.put("key2", "${age}name");
MutablePropertyValues innerPvs = new MutablePropertyValues();
innerPvs.add("country", "${os.name}");
RootBeanDefinition innerBd = new RootBeanDefinition(TestBean.class);
@@ -17,6 +17,7 @@
package org.springframework.beans.factory.support;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URI;
@@ -33,6 +34,8 @@ import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
@@ -406,7 +409,12 @@ class BeanFactoryGenericsTests {
@Test
void testGenericMapWithCollectionValueConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(registry -> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)));
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
}
});
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, AbstractCollection<?>> input = new HashMap<>();
@@ -560,7 +568,12 @@ class BeanFactoryGenericsTests {
@Test
void testGenericMapWithCollectionValueFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(registry -> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)));
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
}
});
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -997,8 +1010,11 @@ class BeanFactoryGenericsTests {
@SuppressWarnings("unchecked")
public <T> T createMock(Class<T> toMock) {
return (T) Proxy.newProxyInstance(BeanFactoryGenericsTests.class.getClassLoader(), new Class<?>[] {toMock},
(InvocationHandler) (proxy, method, args) -> {
throw new UnsupportedOperationException("mocked!");
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
throw new UnsupportedOperationException("mocked!");
}
});
}
}
@@ -18,6 +18,8 @@ package org.springframework.beans.factory.support;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.testfixture.beans.DerivedTestBean;
import org.springframework.beans.testfixture.beans.TestBean;
@@ -38,7 +40,12 @@ public class DefaultSingletonBeanRegistryTests {
beanRegistry.registerSingleton("tb", tb);
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", () -> new TestBean());
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return new TestBean();
}
});
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,8 +34,11 @@ public class ManagedListTests {
@Test
public void mergeSunnyDay() {
ManagedList parent = ManagedList.of("one", "two");
ManagedList child = ManagedList.of("three");
ManagedList parent = new ManagedList();
parent.add("one");
parent.add("two");
ManagedList child = new ManagedList();
child.add("three");
child.setMergeEnabled(true);
List mergedList = child.merge(parent);
assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(3);
@@ -43,7 +46,8 @@ public class ManagedListTests {
@Test
public void mergeWithNullParent() {
ManagedList child = ManagedList.of("one");
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
assertThat(child.merge(null)).isSameAs(child);
}
@@ -57,7 +61,8 @@ public class ManagedListTests {
@Test
public void mergeWithNonCompatibleParentType() {
ManagedList child = ManagedList.of("one");
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
assertThatIllegalArgumentException().isThrownBy(() ->
child.merge("hello"));
@@ -65,7 +70,9 @@ public class ManagedListTests {
@Test
public void mergeEmptyChild() {
ManagedList parent = ManagedList.of("one", "two");
ManagedList parent = new ManagedList();
parent.add("one");
parent.add("two");
ManagedList child = new ManagedList();
child.setMergeEnabled(true);
List mergedList = child.merge(parent);
@@ -75,8 +82,11 @@ public class ManagedListTests {
@Test
public void mergeChildValuesOverrideTheParents() {
// doesn't make much sense in the context of a list...
ManagedList parent = ManagedList.of("one", "two");
ManagedList child = ManagedList.of("one");
ManagedList parent = new ManagedList();
parent.add("one");
parent.add("two");
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
List mergedList = child.merge(parent);
assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(3);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.beans.factory.support;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map;
import org.junit.jupiter.api.Test;
@@ -35,9 +34,11 @@ public class ManagedMapTests {
@Test
public void mergeSunnyDay() {
ManagedMap parent = ManagedMap.ofEntries(new SimpleEntry<>("one", "one"),
new SimpleEntry<>("two", "two"));
ManagedMap child = ManagedMap.ofEntries(new SimpleEntry<>("tree", "three"));
ManagedMap parent = new ManagedMap();
parent.put("one", "one");
parent.put("two", "two");
ManagedMap child = new ManagedMap();
child.put("three", "three");
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(3);
@@ -66,8 +67,9 @@ public class ManagedMapTests {
@Test
public void mergeEmptyChild() {
ManagedMap parent = ManagedMap.ofEntries(new SimpleEntry<>("one", "one"),
new SimpleEntry<>("two", "two"));
ManagedMap parent = new ManagedMap();
parent.put("one", "one");
parent.put("two", "two");
ManagedMap child = new ManagedMap();
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
@@ -76,9 +78,11 @@ public class ManagedMapTests {
@Test
public void mergeChildValuesOverrideTheParents() {
ManagedMap parent = ManagedMap.ofEntries(new SimpleEntry<>("one", "one"),
new SimpleEntry<>("two", "two"));
ManagedMap child = ManagedMap.ofEntries(new SimpleEntry<>("one", "fork"));
ManagedMap parent = new ManagedMap();
parent.put("one", "one");
parent.put("two", "two");
ManagedMap child = new ManagedMap();
child.put("one", "fork");
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
// child value for 'one' must override parent value...
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,8 +34,10 @@ public class ManagedSetTests {
@Test
public void mergeSunnyDay() {
ManagedSet parent = ManagedSet.of("one", "two");
ManagedSet child = ManagedSet.of("three");
ManagedSet parent = new ManagedSet();
parent.add("one");
parent.add("two");
ManagedSet child = new ManagedSet();
child.add("three");
child.setMergeEnabled(true);
Set mergedSet = child.merge(parent);
@@ -44,7 +46,8 @@ public class ManagedSetTests {
@Test
public void mergeWithNullParent() {
ManagedSet child = ManagedSet.of("one");
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
assertThat(child.merge(null)).isSameAs(child);
}
@@ -57,7 +60,8 @@ public class ManagedSetTests {
@Test
public void mergeWithNonCompatibleParentType() {
ManagedSet child = ManagedSet.of("one");
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
assertThatIllegalArgumentException().isThrownBy(() ->
child.merge("hello"));
@@ -65,7 +69,9 @@ public class ManagedSetTests {
@Test
public void mergeEmptyChild() {
ManagedSet parent = ManagedSet.of("one", "two");
ManagedSet parent = new ManagedSet();
parent.add("one");
parent.add("two");
ManagedSet child = new ManagedSet();
child.setMergeEnabled(true);
Set mergedSet = child.merge(parent);
@@ -75,8 +81,11 @@ public class ManagedSetTests {
@Test
public void mergeChildValuesOverrideTheParents() {
// asserts that the set contract is not violated during a merge() operation...
ManagedSet parent = ManagedSet.of("one", "two");
ManagedSet child = ManagedSet.of("one");
ManagedSet parent = new ManagedSet();
parent.add("one");
parent.add("two");
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
Set mergedSet = child.merge(parent);
assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(2);
@@ -16,11 +16,9 @@
package org.springframework.beans.factory
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Test
import kotlin.reflect.full.createInstance
/**
* Mock object based tests for ListableBeanFactory Kotlin extensions
@@ -79,12 +77,10 @@ class ListableBeanFactoryExtensionsTests {
verify { lbf.getBeansWithAnnotation(Bar::class.java) }
}
@Suppress("UNUSED_VARIABLE")
@Test
fun `findAnnotationOnBean with String and reified type parameters`() {
val name = "bar"
every { lbf.findAnnotationOnBean(name, Bar::class.java) } returns Bar::class.createInstance()
val annotation: Bar? = lbf.findAnnotationOnBean(name)
lbf.findAnnotationOnBean<Bar>(name)
verify { lbf.findAnnotationOnBean(name, Bar::class.java) }
}
@@ -40,9 +40,8 @@ public class MustBeInitialized implements InitializingBean {
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited) {
if (!this.inited)
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
}
}
}
@@ -39,18 +39,12 @@ public class Pet {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Pet pet = (Pet) o;
if (name != null ? !name.equals(pet.name) : pet.name != null) {
return false;
}
if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
return true;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 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.
@@ -171,7 +171,6 @@ public class WorkManagerTaskExecutor extends JndiLocatorSupport
}
}
@Deprecated
@Override
public void execute(Runnable task, long startTimeout) {
execute(task);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,7 +76,6 @@ public class SimpleThreadPoolTaskExecutor extends SimpleThreadPool
}
}
@Deprecated
@Override
public void execute(Runnable task, long startTimeout) {
execute(task);
@@ -178,11 +178,14 @@ public class CaffeineCacheManagerTests {
@Test
public void cacheLoaderUseLoadingCache() {
CaffeineCacheManager cm = new CaffeineCacheManager("c1");
cm.setCacheLoader(key -> {
if ("ping".equals(key)) {
return "pong";
cm.setCacheLoader(new CacheLoader<Object, Object>() {
@Override
public Object load(Object key) throws Exception {
if ("ping".equals(key)) {
return "pong";
}
throw new IllegalArgumentException("I only know ping");
}
throw new IllegalArgumentException("I only know ping");
});
Cache cache1 = cm.getCache("c1");
Cache.ValueWrapper value = cache1.get("ping");
@@ -182,9 +182,12 @@ public class JavaMailSenderTests {
final List<Message> messages = new ArrayList<>();
MimeMessagePreparator preparator = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org"));
messages.add(mimeMessage);
MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org"));
messages.add(mimeMessage);
}
};
sender.send(preparator);
@@ -205,13 +208,19 @@ public class JavaMailSenderTests {
final List<Message> messages = new ArrayList<>();
MimeMessagePreparator preparator1 = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
messages.add(mimeMessage);
MimeMessagePreparator preparator1 = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
messages.add(mimeMessage);
}
};
MimeMessagePreparator preparator2 = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
messages.add(mimeMessage);
MimeMessagePreparator preparator2 = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
messages.add(mimeMessage);
}
};
sender.send(preparator1, preparator2);
@@ -314,7 +323,12 @@ public class JavaMailSenderTests {
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
MockJavaMailSender sender = new MockJavaMailSender();
MimeMessagePreparator preparator = mimeMessage -> mimeMessage.setFrom(new InternetAddress(""));
MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setFrom(new InternetAddress(""));
}
};
try {
sender.send(preparator);
}
@@ -1,105 +0,0 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.Cache;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* A {@link CacheErrorHandler} implementation that logs error message. Can be
* used when underlying cache errors should be ignored.
*
* @author Adam Ostrožlík
* @author Stephane Nicoll
* @since 5.3.16
*/
public class LoggingCacheErrorHandler implements CacheErrorHandler {
private final Log logger;
private final boolean logStacktrace;
/**
* Create an instance with the {@link Log logger} to use.
* @param logger the logger to use
* @param logStacktrace whether to log stack trace
*/
public LoggingCacheErrorHandler(Log logger, boolean logStacktrace) {
Assert.notNull(logger, "Logger must not be null");
this.logger = logger;
this.logStacktrace = logStacktrace;
}
/**
* Create an instance that does not log stack traces.
*/
public LoggingCacheErrorHandler() {
this(LogFactory.getLog(LoggingCacheErrorHandler.class), false);
}
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
logCacheError(logger,
createMessage(cache, "failed to get entry with key '" + key + "'"),
exception);
}
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, @Nullable Object value) {
logCacheError(logger,
createMessage(cache, "failed to put entry with key '" + key + "'"),
exception);
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
logCacheError(logger,
createMessage(cache, "failed to evict entry with key '" + key + "'"),
exception);
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
logCacheError(logger, createMessage(cache, "failed to clear entries"), exception);
}
/**
* Log the specified message.
* @param logger the logger
* @param message the message
* @param ex the exception
*/
protected void logCacheError(Log logger, String message, RuntimeException ex) {
if (this.logStacktrace) {
logger.warn(message, ex);
}
else {
logger.warn(message);
}
}
private String createMessage(Cache cache, String reason) {
return String.format("Cache '%s' %s", cache.getName(), reason);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,12 +24,10 @@ import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PlaceholderConfigurerSupport;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.ConfigurablePropertyResolver;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySources;
import org.springframework.core.env.PropertySourcesPropertyResolver;
@@ -59,7 +57,6 @@ import org.springframework.util.StringValueResolver;
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.1
* @see org.springframework.core.env.ConfigurableEnvironment
* @see org.springframework.beans.factory.config.PlaceholderConfigurerSupport
@@ -132,25 +129,12 @@ public class PropertySourcesPlaceholderConfigurer extends PlaceholderConfigurerS
if (this.propertySources == null) {
this.propertySources = new MutablePropertySources();
if (this.environment != null) {
PropertyResolver propertyResolver = this.environment;
// If the ignoreUnresolvablePlaceholders flag is set to true, we have to create a
// local PropertyResolver to enforce that setting, since the Environment is most
// likely not configured with ignoreUnresolvablePlaceholders set to true.
// See https://github.com/spring-projects/spring-framework/issues/27947
if (this.ignoreUnresolvablePlaceholders && (this.environment instanceof ConfigurableEnvironment)) {
ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) this.environment;
PropertySourcesPropertyResolver resolver =
new PropertySourcesPropertyResolver(configurableEnvironment.getPropertySources());
resolver.setIgnoreUnresolvableNestedPlaceholders(true);
propertyResolver = resolver;
}
PropertyResolver propertyResolverToUse = propertyResolver;
this.propertySources.addLast(
new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
@Override
@Nullable
public String getProperty(String key) {
return propertyResolverToUse.getProperty(key);
return this.source.getProperty(key);
}
}
);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 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,7 +147,6 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
this.adaptedExecutor.execute(task);
}
@Deprecated
@Override
public void execute(Runnable task, long startTimeout) {
this.adaptedExecutor.execute(task, startTimeout);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -340,7 +340,6 @@ public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
}
}
@Deprecated
@Override
public void execute(Runnable task, long startTimeout) {
execute(task);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -282,7 +282,6 @@ public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupport
}
}
@Deprecated
@Override
public void execute(Runnable task, long startTimeout) {
execute(task);
@@ -18,7 +18,6 @@ package org.springframework.scheduling.support;
import java.time.DateTimeException;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.ValueRange;
import java.util.function.BiFunction;
@@ -169,25 +168,22 @@ abstract class CronField {
* day-of-month, month, day-of-week.
*/
protected enum Type {
NANO(ChronoField.NANO_OF_SECOND, ChronoUnit.SECONDS),
SECOND(ChronoField.SECOND_OF_MINUTE, ChronoUnit.MINUTES, ChronoField.NANO_OF_SECOND),
MINUTE(ChronoField.MINUTE_OF_HOUR, ChronoUnit.HOURS, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
HOUR(ChronoField.HOUR_OF_DAY, ChronoUnit.DAYS, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
DAY_OF_MONTH(ChronoField.DAY_OF_MONTH, ChronoUnit.MONTHS, ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
MONTH(ChronoField.MONTH_OF_YEAR, ChronoUnit.YEARS, ChronoField.DAY_OF_MONTH, ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
DAY_OF_WEEK(ChronoField.DAY_OF_WEEK, ChronoUnit.WEEKS, ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND);
NANO(ChronoField.NANO_OF_SECOND),
SECOND(ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
MINUTE(ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
HOUR(ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
DAY_OF_MONTH(ChronoField.DAY_OF_MONTH, ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
MONTH(ChronoField.MONTH_OF_YEAR, ChronoField.DAY_OF_MONTH, ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND),
DAY_OF_WEEK(ChronoField.DAY_OF_WEEK, ChronoField.HOUR_OF_DAY, ChronoField.MINUTE_OF_HOUR, ChronoField.SECOND_OF_MINUTE, ChronoField.NANO_OF_SECOND);
private final ChronoField field;
private final ChronoUnit higherOrder;
private final ChronoField[] lowerOrders;
Type(ChronoField field, ChronoUnit higherOrder, ChronoField... lowerOrders) {
Type(ChronoField field, ChronoField... lowerOrders) {
this.field = field;
this.higherOrder = higherOrder;
this.lowerOrders = lowerOrders;
}
@@ -270,9 +266,10 @@ abstract class CronField {
* @return the rolled forward temporal
*/
public <T extends Temporal & Comparable<? super T>> T rollForward(T temporal) {
T result = this.higherOrder.addTo(temporal, 1);
ValueRange range = result.range(this.field);
return this.field.adjustInto(result, range.getMinimum());
int current = get(temporal);
ValueRange range = temporal.range(this.field);
long amount = range.getMaximum() - current + 1;
return this.field.getBaseUnit().addTo(temporal, amount);
}
/**
@@ -251,46 +251,43 @@ final class QuartzCronField extends CronField {
private static TemporalAdjuster weekdayNearestTo(int dayOfMonth) {
return temporal -> {
int current = Type.DAY_OF_MONTH.get(temporal);
DayOfWeek dayOfWeek = DayOfWeek.from(temporal);
int dayOfWeek = temporal.get(ChronoField.DAY_OF_WEEK);
if ((current == dayOfMonth && isWeekday(dayOfWeek)) || // dayOfMonth is a weekday
(dayOfWeek == DayOfWeek.FRIDAY && current == dayOfMonth - 1) || // dayOfMonth is a Saturday, so Friday before
(dayOfWeek == DayOfWeek.MONDAY && current == dayOfMonth + 1) || // dayOfMonth is a Sunday, so Monday after
(dayOfWeek == DayOfWeek.MONDAY && dayOfMonth == 1 && current == 3)) { // dayOfMonth is Saturday 1st, so Monday 3rd
if ((current == dayOfMonth && dayOfWeek < 6) || // dayOfMonth is a weekday
(dayOfWeek == 5 && current == dayOfMonth - 1) || // dayOfMonth is a Saturday, so Friday before
(dayOfWeek == 1 && current == dayOfMonth + 1) || // dayOfMonth is a Sunday, so Monday after
(dayOfWeek == 1 && dayOfMonth == 1 && current == 3)) { // dayOfMonth is the 1st, so Monday 3rd
return temporal;
}
int count = 0;
while (count++ < CronExpression.MAX_ATTEMPTS) {
temporal = Type.DAY_OF_MONTH.elapseUntil(cast(temporal), dayOfMonth);
temporal = atMidnight().adjustInto(temporal);
current = Type.DAY_OF_MONTH.get(temporal);
if (current == dayOfMonth) {
dayOfWeek = DayOfWeek.from(temporal);
dayOfWeek = temporal.get(ChronoField.DAY_OF_WEEK);
if (dayOfWeek == DayOfWeek.SATURDAY) {
if (dayOfWeek == 6) { // Saturday
if (dayOfMonth != 1) {
temporal = temporal.minus(1, ChronoUnit.DAYS);
return temporal.minus(1, ChronoUnit.DAYS);
}
else {
// exception for "1W" fields: execute on next Monday
temporal = temporal.plus(2, ChronoUnit.DAYS);
// exception for "1W" fields: execute on nearest Monday
return temporal.plus(2, ChronoUnit.DAYS);
}
}
else if (dayOfWeek == DayOfWeek.SUNDAY) {
temporal = temporal.plus(1, ChronoUnit.DAYS);
else if (dayOfWeek == 7) { // Sunday
return temporal.plus(1, ChronoUnit.DAYS);
}
else {
return temporal;
}
return atMidnight().adjustInto(temporal);
}
else {
temporal = Type.DAY_OF_MONTH.elapseUntil(cast(temporal), dayOfMonth);
current = Type.DAY_OF_MONTH.get(temporal);
}
}
return null;
};
}
private static boolean isWeekday(DayOfWeek dayOfWeek) {
return dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY;
}
/**
* Return a temporal adjuster that finds the last of the given doy-of-week
* in a month.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ import org.springframework.core.annotation.AliasFor;
* @see org.springframework.web.bind.annotation.RequestMapping
* @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner
*/
@Target(ElementType.TYPE)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ import org.springframework.core.annotation.AliasFor;
* @see org.springframework.dao.DataAccessException
* @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
*/
@Target(ElementType.TYPE)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ import org.springframework.core.annotation.AliasFor;
* @see Component
* @see Repository
*/
@Target(ElementType.TYPE)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.aop.aspectj.autoproxy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
@@ -28,8 +27,6 @@ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
@@ -45,11 +42,6 @@ import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.testfixture.beans.ITestBean;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.NestedRuntimeException;
@@ -300,16 +292,6 @@ public class AspectJAutoProxyCreatorTests {
assertThat(tb.getAge()).isEqualTo(68);
}
@ParameterizedTest(name = "[{index}] {0}")
@ValueSource(classes = {ProxyTargetClassFalseConfig.class, ProxyTargetClassTrueConfig.class})
void lambdaIsAlwaysProxiedWithJdkProxy(Class<?> configClass) {
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configClass)) {
Supplier<?> supplier = context.getBean(Supplier.class);
assertThat(AopUtils.isAopProxy(supplier)).as("AOP proxy").isTrue();
assertThat(AopUtils.isJdkDynamicProxy(supplier)).as("JDK Dynamic proxy").isTrue();
assertThat(supplier.get()).asString().isEqualTo("advised: lambda");
}
}
/**
* Returns a new {@link ClassPathXmlApplicationContext} for the file ending in <var>fileSuffix</var>.
@@ -575,7 +557,12 @@ class TestBeanAdvisor extends StaticMethodMatcherPointcutAdvisor {
public int count;
public TestBeanAdvisor() {
setAdvice((MethodBeforeAdvice) (method, args, target) -> ++count);
setAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
++count;
}
});
}
@Override
@@ -584,35 +571,3 @@ class TestBeanAdvisor extends StaticMethodMatcherPointcutAdvisor {
}
}
abstract class AbstractProxyTargetClassConfig {
@Bean
Supplier<String> stringSupplier() {
return () -> "lambda";
}
@Bean
SupplierAdvice supplierAdvice() {
return new SupplierAdvice();
}
@Aspect
static class SupplierAdvice {
@Around("execution(public * org.springframework.aop.aspectj.autoproxy..*.*(..))")
Object aroundSupplier(ProceedingJoinPoint joinPoint) throws Throwable {
return "advised: " + joinPoint.proceed();
}
}
}
@Configuration(proxyBeanMethods = false)
@EnableAspectJAutoProxy(proxyTargetClass = false)
class ProxyTargetClassFalseConfig extends AbstractProxyTargetClassConfig {
}
@Configuration(proxyBeanMethods = false)
@EnableAspectJAutoProxy(proxyTargetClass = true)
class ProxyTargetClassTrueConfig extends AbstractProxyTargetClassConfig {
}
@@ -372,14 +372,17 @@ public abstract class AbstractAopProxyTests {
private void testContext(final boolean context) throws Throwable {
final String s = "foo";
// Test return value
MethodInterceptor mi = invocation -> {
if (!context) {
assertNoInvocationContext();
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (!context) {
assertNoInvocationContext();
}
else {
assertThat(ExposeInvocationInterceptor.currentInvocation()).as("have context").isNotNull();
}
return s;
}
else {
assertThat(ExposeInvocationInterceptor.currentInvocation()).as("have context").isNotNull();
}
return s;
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
if (context) {
@@ -419,8 +422,11 @@ public abstract class AbstractAopProxyTests {
public void testDeclaredException() throws Throwable {
final Exception expectedException = new Exception();
// Test return value
MethodInterceptor mi = invocation -> {
throw expectedException;
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
throw expectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
@@ -447,8 +453,11 @@ public abstract class AbstractAopProxyTests {
public void testUndeclaredCheckedException() throws Throwable {
final Exception unexpectedException = new Exception();
// Test return value
MethodInterceptor mi = invocation -> {
throw unexpectedException;
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
throw unexpectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
@@ -468,8 +477,11 @@ public abstract class AbstractAopProxyTests {
public void testUndeclaredUncheckedException() throws Throwable {
final RuntimeException unexpectedException = new RuntimeException();
// Test return value
MethodInterceptor mi = invocation -> {
throw unexpectedException;
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
throw unexpectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
@@ -648,7 +660,12 @@ public abstract class AbstractAopProxyTests {
NopInterceptor di = new NopInterceptor();
pc.addAdvice(di);
final long ts = 37;
pc.addAdvice(new DelegatingIntroductionInterceptor((TimeStamped) () -> ts));
pc.addAdvice(new DelegatingIntroductionInterceptor(new TimeStamped() {
@Override
public long getTimeStamp() {
return ts;
}
}));
ITestBean proxied = (ITestBean) createProxy(pc);
assertThat(proxied.getName()).isEqualTo(name);
@@ -1022,14 +1039,17 @@ public abstract class AbstractAopProxyTests {
ProxyFactory pc = new ProxyFactory(tb);
pc.addInterface(ITestBean.class);
MethodInterceptor twoBirthdayInterceptor = mi -> {
// Clone the invocation to proceed three times
// "The Moor's Last Sigh": this technology can cause premature aging
MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone();
clone1.proceed();
clone2.proceed();
return mi.proceed();
MethodInterceptor twoBirthdayInterceptor = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// Clone the invocation to proceed three times
// "The Moor's Last Sigh": this technology can cause premature aging
MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone();
clone1.proceed();
clone2.proceed();
return mi.proceed();
}
};
@SuppressWarnings("serial")
StaticMethodMatcherPointcutAdvisor advisor = new StaticMethodMatcherPointcutAdvisor(twoBirthdayInterceptor) {
@@ -1062,13 +1082,16 @@ public abstract class AbstractAopProxyTests {
/**
* Changes the name, then changes it back.
*/
MethodInterceptor nameReverter = mi -> {
MethodInvocation clone = ((ReflectiveMethodInvocation) mi).invocableClone();
String oldName = ((ITestBean) mi.getThis()).getName();
clone.getArguments()[0] = oldName;
// Original method invocation should be unaffected by changes to argument list of clone
mi.proceed();
return clone.proceed();
MethodInterceptor nameReverter = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
MethodInvocation clone = ((ReflectiveMethodInvocation) mi).invocableClone();
String oldName = ((ITestBean) mi.getThis()).getName();
clone.getArguments()[0] = oldName;
// Original method invocation should be unaffected by changes to argument list of clone
mi.proceed();
return clone.proceed();
}
};
class NameSaver implements MethodInterceptor {
@@ -1324,9 +1347,8 @@ public abstract class AbstractAopProxyTests {
@Override
public void before(Method m, Object[] args, Object target) throws Throwable {
super.before(m, args, target);
if (m.getName().startsWith("set")) {
if (m.getName().startsWith("set"))
throw rex;
}
}
};
@@ -1541,10 +1563,13 @@ public abstract class AbstractAopProxyTests {
@SuppressWarnings("serial")
protected static class StringSetterNullReplacementAdvice extends DefaultPointcutAdvisor {
private static MethodInterceptor cleaner = mi -> {
// We know it can only be invoked if there's a single parameter of type string
mi.getArguments()[0] = "";
return mi.proceed();
private static MethodInterceptor cleaner = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// We know it can only be invoked if there's a single parameter of type string
mi.getArguments()[0] = "";
return mi.proceed();
}
};
public StringSetterNullReplacementAdvice() {
@@ -1576,9 +1601,7 @@ public abstract class AbstractAopProxyTests {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
boolean run = m.getName().contains(pattern);
if (run) {
++count;
}
if (run) ++count;
return run;
}
});
@@ -1597,9 +1620,7 @@ public abstract class AbstractAopProxyTests {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
boolean run = m.getName().contains(pattern);
if (run) {
++count;
}
if (run) ++count;
return run;
}
@Override
@@ -1903,9 +1924,8 @@ public abstract class AbstractAopProxyTests {
*/
@Override
public void releaseTarget(Object pTarget) throws Exception {
if (pTarget != this.target) {
if (pTarget != this.target)
throw new RuntimeException("Released wrong target");
}
++releases;
}
@@ -1914,9 +1934,8 @@ public abstract class AbstractAopProxyTests {
*
*/
public void verify() {
if (gets != releases) {
if (gets != releases)
throw new RuntimeException("Expectation failed: " + gets + " gets and " + releases + " releases");
}
}
/**
@@ -198,16 +198,10 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (!name.equals(person.name)) {
return false;
}
if (!name.equals(person.name)) return false;
return true;
}
@@ -304,8 +304,11 @@ public class ProxyFactoryBeanTests {
final Exception ex = new UnsupportedOperationException("invoke");
// Add evil interceptor to head of list
config.addAdvice(0, (MethodInterceptor) invocation -> {
throw ex;
config.addAdvice(0, new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
throw ex;
}
});
assertThat(config.getAdvisors().length).as("Have correct advisor count").isEqualTo(2);
@@ -688,9 +691,12 @@ public class ProxyFactoryBeanTests {
}
public PointcutForVoid() {
setAdvice((MethodInterceptor) invocation -> {
methodNames.add(invocation.getMethod().getName());
return invocation.proceed();
setAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
methodNames.add(invocation.getMethod().getName());
return invocation.proceed();
}
});
setPointcut(new DynamicMethodMatcherPointcut() {
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
package org.springframework.aop.framework.autoproxy;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.aopalliance.intercept.MethodInterceptor;
@@ -432,7 +434,6 @@ public class AutoProxyCreatorTests {
@SuppressWarnings("serial")
public static class IntroductionTestAutoProxyCreator extends TestAutoProxyCreator {
@Override
protected Object[] getAdvicesAndAdvisors() {
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(this.testInterceptor);
advisor.addInterface(Serializable.class);
@@ -490,8 +491,12 @@ public class AutoProxyCreatorTests {
@Override
public ITestBean getObject() {
return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class},
(proxy, method, args) -> ReflectionUtils.invokeMethod(method, tb, args));
return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return ReflectionUtils.invokeMethod(method, tb, args);
}
});
}
@Override
@@ -158,8 +158,8 @@ class CommonsPool2TargetSourceTests {
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (Object element : pooledInstances) {
targetSource.releaseTarget(element);
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
}
}
@@ -1,76 +0,0 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import org.springframework.cache.support.NoOpCache;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link LoggingCacheErrorHandler}.
*
* @author Adam Ostrožlík
* @author Stephane Nicoll
*/
public class LoggingCacheErrorHandlerTests {
@Test
void handleGetCacheErrorLogsAppropriateMessage() {
Log logger = mock(Log.class);
LoggingCacheErrorHandler handler = new LoggingCacheErrorHandler(logger, false);
handler.handleCacheGetError(new RuntimeException(), new NoOpCache("NOOP"), "key");
verify(logger).warn("Cache 'NOOP' failed to get entry with key 'key'");
}
@Test
void handlePutCacheErrorLogsAppropriateMessage() {
Log logger = mock(Log.class);
LoggingCacheErrorHandler handler = new LoggingCacheErrorHandler(logger, false);
handler.handleCachePutError(new RuntimeException(), new NoOpCache("NOOP"), "key", new Object());
verify(logger).warn("Cache 'NOOP' failed to put entry with key 'key'");
}
@Test
void handleEvictCacheErrorLogsAppropriateMessage() {
Log logger = mock(Log.class);
LoggingCacheErrorHandler handler = new LoggingCacheErrorHandler(logger, false);
handler.handleCacheEvictError(new RuntimeException(), new NoOpCache("NOOP"), "key");
verify(logger).warn("Cache 'NOOP' failed to evict entry with key 'key'");
}
@Test
void handleClearErrorLogsAppropriateMessage() {
Log logger = mock(Log.class);
LoggingCacheErrorHandler handler = new LoggingCacheErrorHandler(logger, false);
handler.handleCacheClearError(new RuntimeException(), new NoOpCache("NOOP"));
verify(logger).warn("Cache 'NOOP' failed to clear entries");
}
@Test
void handleCacheErrorWithStacktrace() {
Log logger = mock(Log.class);
LoggingCacheErrorHandler handler = new LoggingCacheErrorHandler(logger, true);
RuntimeException exception = new RuntimeException();
handler.handleCacheGetError(exception, new NoOpCache("NOOP"), "key");
verify(logger).warn("Cache 'NOOP' failed to get entry with key 'key'", exception);
}
}
@@ -33,24 +33,21 @@ public class LifecycleContextBean extends LifecycleBean implements ApplicationCo
@Override
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (this.owningContext != null) {
if (this.owningContext != null)
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
}
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.owningContext == null) {
if (this.owningContext == null)
throw new RuntimeException("Factory didn't call setApplicationContext before afterPropertiesSet on lifecycle bean");
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.owningFactory == null) {
if (this.owningFactory == null)
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
}
this.owningContext = applicationContext;
}
@@ -544,24 +544,19 @@ class TestBean {
@Override
public boolean equals(Object obj) {
if (this == obj) {
if (this == obj)
return true;
}
if (obj == null) {
if (obj == null)
return false;
}
if (getClass() != obj.getClass()) {
if (getClass() != obj.getClass())
return false;
}
TestBean other = (TestBean) obj;
if (name == null) {
if (other.name != null) {
if (other.name != null)
return false;
}
}
else if (!name.equals(other.name)) {
else if (!name.equals(other.name))
return false;
}
return true;
}
@@ -215,7 +215,12 @@ public class CommonAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean4", tbd);
bf.registerResolvableDependency(BeanFactory.class, bf);
bf.registerResolvableDependency(INestedTestBean.class, (ObjectFactory<Object>) () -> new NestedTestBean());
bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return new NestedTestBean();
}
});
@SuppressWarnings("deprecation")
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ppc = new org.springframework.beans.factory.config.PropertyPlaceholderConfigurer();
@@ -18,8 +18,10 @@ package org.springframework.context.annotation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.testfixture.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
@@ -70,8 +72,11 @@ public class ConfigurationClassAndBFPPTests {
@Bean
public BeanFactoryPostProcessor bfpp() {
return beanFactory -> {
// no-op
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// no-op
}
};
}
}
@@ -83,8 +88,11 @@ public class ConfigurationClassAndBFPPTests {
@Bean
public static final BeanFactoryPostProcessor bfpp() {
return beanFactory -> {
// no-op
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// no-op
}
};
}
}
@@ -291,9 +291,7 @@ public class ConfigurationClassWithConditionTests {
static class ImportsNotCreated {
static {
if (true) {
throw new RuntimeException();
}
if (true) throw new RuntimeException();
}
}
@@ -301,18 +299,14 @@ public class ConfigurationClassWithConditionTests {
static class ConfigurationNotCreated {
static {
if (true) {
throw new RuntimeException();
}
if (true) throw new RuntimeException();
}
}
static class RegistrarNotCreated implements ImportBeanDefinitionRegistrar {
static {
if (true) {
throw new RuntimeException();
}
if (true) throw new RuntimeException();
}
@Override
@@ -324,9 +318,7 @@ public class ConfigurationClassWithConditionTests {
static class ImportSelectorNotCreated implements ImportSelector {
static {
if (true) {
throw new RuntimeException();
}
if (true) throw new RuntimeException();
}
@Override
@@ -1,279 +0,0 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests which verify expected <em>init</em> and <em>destroy</em> bean lifecycle
* behavior as requested in
* <a href="https://github.com/spring-projects/spring-framework/issues/8455" target="_blank">SPR-3775</a>.
*
* <p>Specifically, combinations of the following are tested:
* <ul>
* <li>{@link InitializingBean} &amp; {@link DisposableBean} interfaces</li>
* <li>Custom {@link RootBeanDefinition#getInitMethodName() init} &amp;
* {@link RootBeanDefinition#getDestroyMethodName() destroy} methods</li>
* <li>JSR 250's {@link javax.annotation.PostConstruct @PostConstruct} &amp;
* {@link javax.annotation.PreDestroy @PreDestroy} annotations</li>
* </ul>
*
* @author Sam Brannen
* @since 2.5
*/
class InitDestroyMethodLifecycleTests {
@Test
void initDestroyMethods() {
Class<?> beanClass = InitDestroyBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "afterPropertiesSet", "destroy");
InitDestroyBean bean = beanFactory.getBean(InitDestroyBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("afterPropertiesSet");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("destroy");
}
@Test
void initializingDisposableInterfaces() {
Class<?> beanClass = CustomInitializingDisposableBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit", "customDestroy");
CustomInitializingDisposableBean bean = beanFactory.getBean(CustomInitializingDisposableBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("afterPropertiesSet", "customInit");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("destroy", "customDestroy");
}
@Test
void initializingDisposableInterfacesWithShadowedMethods() {
Class<?> beanClass = InitializingDisposableWithShadowedMethodsBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "afterPropertiesSet", "destroy");
InitializingDisposableWithShadowedMethodsBean bean = beanFactory.getBean(InitializingDisposableWithShadowedMethodsBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("InitializingBean.afterPropertiesSet");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("DisposableBean.destroy");
}
@Test
void jsr250Annotations() {
Class<?> beanClass = CustomAnnotatedInitDestroyBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit", "customDestroy");
CustomAnnotatedInitDestroyBean bean = beanFactory.getBean(CustomAnnotatedInitDestroyBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("postConstruct", "afterPropertiesSet", "customInit");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("preDestroy", "destroy", "customDestroy");
}
@Test
void jsr250AnnotationsWithShadowedMethods() {
Class<?> beanClass = CustomAnnotatedInitDestroyWithShadowedMethodsBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit", "customDestroy");
CustomAnnotatedInitDestroyWithShadowedMethodsBean bean = beanFactory.getBean(CustomAnnotatedInitDestroyWithShadowedMethodsBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("@PostConstruct.afterPropertiesSet", "customInit");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("@PreDestroy.destroy", "customDestroy");
}
@Test
void jsr250AnnotationsWithCustomPrivateInitDestroyMethods() {
Class<?> beanClass = CustomAnnotatedPrivateInitDestroyBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit1", "customDestroy1");
CustomAnnotatedPrivateInitDestroyBean bean = beanFactory.getBean(CustomAnnotatedPrivateInitDestroyBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("@PostConstruct.privateCustomInit1", "afterPropertiesSet");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("@PreDestroy.privateCustomDestroy1", "destroy");
}
@Test
void jsr250AnnotationsWithCustomSameMethodNames() {
Class<?> beanClass = CustomAnnotatedPrivateSameNameInitDestroyBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit1", "customDestroy1");
CustomAnnotatedPrivateSameNameInitDestroyBean bean = beanFactory.getBean(CustomAnnotatedPrivateSameNameInitDestroyBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("@PostConstruct.privateCustomInit1", "@PostConstruct.sameNameCustomInit1", "afterPropertiesSet");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("@PreDestroy.sameNameCustomDestroy1", "@PreDestroy.privateCustomDestroy1", "destroy");
}
@Test
void allLifecycleMechanismsAtOnce() {
Class<?> beanClass = AllInOneBean.class;
DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "afterPropertiesSet", "destroy");
AllInOneBean bean = beanFactory.getBean(AllInOneBean.class);
assertThat(bean.initMethods).as("init-methods").containsExactly("afterPropertiesSet");
beanFactory.destroySingletons();
assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("destroy");
}
private static DefaultListableBeanFactory createBeanFactoryAndRegisterBean(Class<?> beanClass,
String initMethodName, String destroyMethodName) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setInitMethodName(initMethodName);
beanDefinition.setDestroyMethodName(destroyMethodName);
beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
beanFactory.registerBeanDefinition("lifecycleTestBean", beanDefinition);
return beanFactory;
}
static class InitDestroyBean {
final List<String> initMethods = new ArrayList<>();
final List<String> destroyMethods = new ArrayList<>();
public void afterPropertiesSet() throws Exception {
this.initMethods.add("afterPropertiesSet");
}
public void destroy() throws Exception {
this.destroyMethods.add("destroy");
}
}
static class InitializingDisposableWithShadowedMethodsBean extends InitDestroyBean implements
InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("InitializingBean.afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
this.destroyMethods.add("DisposableBean.destroy");
}
}
static class CustomInitDestroyBean {
final List<String> initMethods = new ArrayList<>();
final List<String> destroyMethods = new ArrayList<>();
public void customInit() throws Exception {
this.initMethods.add("customInit");
}
public void customDestroy() throws Exception {
this.destroyMethods.add("customDestroy");
}
}
static class CustomAnnotatedPrivateInitDestroyBean extends CustomInitializingDisposableBean {
@PostConstruct
private void customInit1() throws Exception {
this.initMethods.add("@PostConstruct.privateCustomInit1");
}
@PreDestroy
private void customDestroy1() throws Exception {
this.destroyMethods.add("@PreDestroy.privateCustomDestroy1");
}
}
static class CustomAnnotatedPrivateSameNameInitDestroyBean extends CustomAnnotatedPrivateInitDestroyBean {
@PostConstruct
@SuppressWarnings("unused")
private void customInit1() throws Exception {
this.initMethods.add("@PostConstruct.sameNameCustomInit1");
}
@PreDestroy
@SuppressWarnings("unused")
private void customDestroy1() throws Exception {
this.destroyMethods.add("@PreDestroy.sameNameCustomDestroy1");
}
}
static class CustomInitializingDisposableBean extends CustomInitDestroyBean
implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
this.destroyMethods.add("destroy");
}
}
static class CustomAnnotatedInitDestroyBean extends CustomInitializingDisposableBean {
@PostConstruct
public void postConstruct() throws Exception {
this.initMethods.add("postConstruct");
}
@PreDestroy
public void preDestroy() throws Exception {
this.destroyMethods.add("preDestroy");
}
}
static class CustomAnnotatedInitDestroyWithShadowedMethodsBean extends CustomInitializingDisposableBean {
@PostConstruct
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("@PostConstruct.afterPropertiesSet");
}
@PreDestroy
@Override
public void destroy() throws Exception {
this.destroyMethods.add("@PreDestroy.destroy");
}
}
static class AllInOneBean implements InitializingBean, DisposableBean {
final List<String> initMethods = new ArrayList<>();
final List<String> destroyMethods = new ArrayList<>();
@PostConstruct
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("afterPropertiesSet");
}
@PreDestroy
@Override
public void destroy() throws Exception {
this.destroyMethods.add("destroy");
}
}
}
@@ -0,0 +1,272 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <p>
* JUnit-3.8-based unit test which verifies expected <em>init</em> and
* <em>destroy</em> bean lifecycle behavior as requested in <a
* href="https://opensource.atlassian.com/projects/spring/browse/SPR-3775"
* target="_blank">SPR-3775</a>.
* </p>
* <p>
* Specifically, combinations of the following are tested:
* </p>
* <ul>
* <li>{@link InitializingBean} &amp; {@link DisposableBean} interfaces</li>
* <li>Custom {@link RootBeanDefinition#getInitMethodName() init} &amp;
* {@link RootBeanDefinition#getDestroyMethodName() destroy} methods</li>
* <li>JSR 250's {@link javax.annotation.PostConstruct @PostConstruct} &amp;
* {@link javax.annotation.PreDestroy @PreDestroy} annotations</li>
* </ul>
*
* @author Sam Brannen
* @since 2.5
*/
public class Spr3775InitDestroyLifecycleTests {
private static final Log logger = LogFactory.getLog(Spr3775InitDestroyLifecycleTests.class);
/** LIFECYCLE_TEST_BEAN. */
private static final String LIFECYCLE_TEST_BEAN = "lifecycleTestBean";
private void debugMethods(Class<?> clazz, String category, List<String> methodNames) {
if (logger.isDebugEnabled()) {
logger.debug(clazz.getSimpleName() + ": " + category + ": " + methodNames);
}
}
private void assertMethodOrdering(Class<?> clazz, String category, List<String> expectedMethods,
List<String> actualMethods) {
debugMethods(clazz, category, actualMethods);
assertThat(ObjectUtils.nullSafeEquals(expectedMethods, actualMethods)).as("Verifying " + category + ": expected<" + expectedMethods + "> but got<" + actualMethods + ">.").isTrue();
}
private DefaultListableBeanFactory createBeanFactoryAndRegisterBean(final Class<?> beanClass,
final String initMethodName, final String destroyMethodName) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setInitMethodName(initMethodName);
beanDefinition.setDestroyMethodName(destroyMethodName);
beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
beanFactory.registerBeanDefinition(LIFECYCLE_TEST_BEAN, beanDefinition);
return beanFactory;
}
@Test
public void testInitDestroyMethods() {
final Class<?> beanClass = InitDestroyBean.class;
final DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass,
"afterPropertiesSet", "destroy");
final InitDestroyBean bean = (InitDestroyBean) beanFactory.getBean(LIFECYCLE_TEST_BEAN);
assertMethodOrdering(beanClass, "init-methods", Arrays.asList("afterPropertiesSet"), bean.initMethods);
beanFactory.destroySingletons();
assertMethodOrdering(beanClass, "destroy-methods", Arrays.asList("destroy"), bean.destroyMethods);
}
@Test
public void testInitializingDisposableInterfaces() {
final Class<?> beanClass = CustomInitializingDisposableBean.class;
final DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit",
"customDestroy");
final CustomInitializingDisposableBean bean = (CustomInitializingDisposableBean) beanFactory.getBean(LIFECYCLE_TEST_BEAN);
assertMethodOrdering(beanClass, "init-methods", Arrays.asList("afterPropertiesSet", "customInit"),
bean.initMethods);
beanFactory.destroySingletons();
assertMethodOrdering(beanClass, "destroy-methods", Arrays.asList("destroy", "customDestroy"),
bean.destroyMethods);
}
@Test
public void testInitializingDisposableInterfacesWithShadowedMethods() {
final Class<?> beanClass = InitializingDisposableWithShadowedMethodsBean.class;
final DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass,
"afterPropertiesSet", "destroy");
final InitializingDisposableWithShadowedMethodsBean bean = (InitializingDisposableWithShadowedMethodsBean) beanFactory.getBean(LIFECYCLE_TEST_BEAN);
assertMethodOrdering(beanClass, "init-methods", Arrays.asList("InitializingBean.afterPropertiesSet"),
bean.initMethods);
beanFactory.destroySingletons();
assertMethodOrdering(beanClass, "destroy-methods", Arrays.asList("DisposableBean.destroy"), bean.destroyMethods);
}
@Test
public void testJsr250Annotations() {
final Class<?> beanClass = CustomAnnotatedInitDestroyBean.class;
final DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit",
"customDestroy");
final CustomAnnotatedInitDestroyBean bean = (CustomAnnotatedInitDestroyBean) beanFactory.getBean(LIFECYCLE_TEST_BEAN);
assertMethodOrdering(beanClass, "init-methods", Arrays.asList("postConstruct", "afterPropertiesSet",
"customInit"), bean.initMethods);
beanFactory.destroySingletons();
assertMethodOrdering(beanClass, "destroy-methods", Arrays.asList("preDestroy", "destroy", "customDestroy"),
bean.destroyMethods);
}
@Test
public void testJsr250AnnotationsWithShadowedMethods() {
final Class<?> beanClass = CustomAnnotatedInitDestroyWithShadowedMethodsBean.class;
final DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass, "customInit",
"customDestroy");
final CustomAnnotatedInitDestroyWithShadowedMethodsBean bean = (CustomAnnotatedInitDestroyWithShadowedMethodsBean) beanFactory.getBean(LIFECYCLE_TEST_BEAN);
assertMethodOrdering(beanClass, "init-methods",
Arrays.asList("@PostConstruct.afterPropertiesSet", "customInit"), bean.initMethods);
beanFactory.destroySingletons();
assertMethodOrdering(beanClass, "destroy-methods", Arrays.asList("@PreDestroy.destroy", "customDestroy"),
bean.destroyMethods);
}
@Test
public void testAllLifecycleMechanismsAtOnce() {
final Class<?> beanClass = AllInOneBean.class;
final DefaultListableBeanFactory beanFactory = createBeanFactoryAndRegisterBean(beanClass,
"afterPropertiesSet", "destroy");
final AllInOneBean bean = (AllInOneBean) beanFactory.getBean(LIFECYCLE_TEST_BEAN);
assertMethodOrdering(beanClass, "init-methods", Arrays.asList("afterPropertiesSet"), bean.initMethods);
beanFactory.destroySingletons();
assertMethodOrdering(beanClass, "destroy-methods", Arrays.asList("destroy"), bean.destroyMethods);
}
public static class InitDestroyBean {
final List<String> initMethods = new ArrayList<>();
final List<String> destroyMethods = new ArrayList<>();
public void afterPropertiesSet() throws Exception {
this.initMethods.add("afterPropertiesSet");
}
public void destroy() throws Exception {
this.destroyMethods.add("destroy");
}
}
public static class InitializingDisposableWithShadowedMethodsBean extends InitDestroyBean implements
InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("InitializingBean.afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
this.destroyMethods.add("DisposableBean.destroy");
}
}
public static class CustomInitDestroyBean {
final List<String> initMethods = new ArrayList<>();
final List<String> destroyMethods = new ArrayList<>();
public void customInit() throws Exception {
this.initMethods.add("customInit");
}
public void customDestroy() throws Exception {
this.destroyMethods.add("customDestroy");
}
}
public static class CustomInitializingDisposableBean extends CustomInitDestroyBean
implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
this.destroyMethods.add("destroy");
}
}
public static class CustomAnnotatedInitDestroyBean extends CustomInitializingDisposableBean {
@PostConstruct
public void postConstruct() throws Exception {
this.initMethods.add("postConstruct");
}
@PreDestroy
public void preDestroy() throws Exception {
this.destroyMethods.add("preDestroy");
}
}
public static class CustomAnnotatedInitDestroyWithShadowedMethodsBean extends CustomInitializingDisposableBean {
@PostConstruct
@Override
public void afterPropertiesSet() throws Exception {
this.initMethods.add("@PostConstruct.afterPropertiesSet");
}
@PreDestroy
@Override
public void destroy() throws Exception {
this.destroyMethods.add("@PreDestroy.destroy");
}
}
public static class AllInOneBean implements InitializingBean, DisposableBean {
final List<String> initMethods = new ArrayList<>();
final List<String> destroyMethods = new ArrayList<>();
@Override
@PostConstruct
public void afterPropertiesSet() throws Exception {
this.initMethods.add("afterPropertiesSet");
}
@Override
@PreDestroy
public void destroy() throws Exception {
this.destroyMethods.add("destroy");
}
}
}
@@ -136,7 +136,10 @@ public class ConfigurationClassAspectIntegrationTests {
@Bean
Runnable fromInnerClass() {
return () -> {
return new Runnable() {
@Override
public void run() {
}
};
}
@@ -39,6 +39,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.ListFactoryBean;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
@@ -558,9 +559,12 @@ public class ConfigurationClassProcessingTests {
// @Bean
public BeanFactoryPostProcessor beanFactoryPostProcessor() {
return beanFactory -> {
BeanDefinition bd = beanFactory.getBeanDefinition("beanPostProcessor");
bd.getPropertyValues().addPropertyValue("nameSuffix", "-processed-" + myProp);
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
BeanDefinition bd = beanFactory.getBeanDefinition("beanPostProcessor");
bd.getPropertyValues().addPropertyValue("nameSuffix", "-processed-" + myProp);
}
};
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 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,6 +20,7 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.jupiter.api.Test;
@@ -140,9 +141,12 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen
ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
smc.setTaskExecutor(command -> {
command.run();
command.run();
smc.setTaskExecutor(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
command.run();
}
});
smc.addApplicationListener(listener);
@@ -425,7 +429,12 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen
public void anonymousClassAsListener() {
final Set<MyEvent> seenEvents = new HashSet<>();
StaticApplicationContext context = new StaticApplicationContext();
context.addApplicationListener((MyEvent event) -> seenEvents.add(event));
context.addApplicationListener(new ApplicationListener<MyEvent>() {
@Override
public void onApplicationEvent(MyEvent event) {
seenEvents.add(event);
}
});
context.refresh();
MyEvent event1 = new MyEvent(context);
@@ -65,7 +65,7 @@ public class PayloadApplicationEventTests {
public void testProgrammaticPayloadListener() {
List<String> events = new ArrayList<>();
ApplicationListener<PayloadApplicationEvent<String>> listener = ApplicationListener.forPayload(events::add);
ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(Integer::intValue);
ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(payload -> payload.intValue());
ConfigurableApplicationContext ac = new GenericApplicationContext();
ac.addApplicationListener(listener);
@@ -36,12 +36,8 @@ public abstract class AbstractIdentifiable implements Identifiable {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractIdentifiable that = (AbstractIdentifiable) o;
@@ -38,12 +38,8 @@ public class GenericEventPojo<T> implements ResolvableTypeProvider {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GenericEventPojo<?> that = (GenericEventPojo<?>) o;
@@ -50,12 +50,8 @@ public abstract class IdentifiableApplicationEvent extends ApplicationEvent impl
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IdentifiableApplicationEvent that = (IdentifiableApplicationEvent) o;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -99,7 +99,8 @@ public class ConversionServiceFactoryBeanTests {
Set<Object> converters = new HashSet<>();
converters.add("bogus");
factory.setConverters(converters);
assertThatIllegalArgumentException().isThrownBy(factory::afterPropertiesSet);
assertThatIllegalArgumentException().isThrownBy(
factory::afterPropertiesSet);
}
@Test
@@ -21,14 +21,9 @@ import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
@@ -45,11 +40,8 @@ import static org.springframework.beans.factory.support.BeanDefinitionBuilder.ge
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
* Tests for {@link PropertySourcesPlaceholderConfigurer}.
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.1
*/
public class PropertySourcesPlaceholderConfigurerTests {
@@ -167,11 +159,8 @@ public class PropertySourcesPlaceholderConfigurerTests {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
//pc.setIgnoreUnresolvablePlaceholders(false); // the default
assertThatExceptionOfType(BeanDefinitionStoreException.class)
.isThrownBy(() -> ppc.postProcessBeanFactory(bf))
.havingCause()
.isExactlyInstanceOf(IllegalArgumentException.class)
.withMessage("Could not resolve placeholder 'my.name' in value \"${my.name}\"");
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
ppc.postProcessBeanFactory(bf));
}
@Test
@@ -188,38 +177,6 @@ public class PropertySourcesPlaceholderConfigurerTests {
assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}");
}
@Test
// https://github.com/spring-projects/spring-framework/issues/27947
public void ignoreUnresolvablePlaceholdersInAtValueAnnotation__falseIsDefault() {
MockPropertySource mockPropertySource = new MockPropertySource("test");
mockPropertySource.setProperty("my.key", "${enigma}");
@SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().getPropertySources().addLast(mockPropertySource);
context.register(IgnoreUnresolvablePlaceholdersFalseConfig.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(context::refresh)
.havingCause()
.isExactlyInstanceOf(IllegalArgumentException.class)
.withMessage("Could not resolve placeholder 'enigma' in value \"${enigma}\"");
}
@Test
// https://github.com/spring-projects/spring-framework/issues/27947
public void ignoreUnresolvablePlaceholdersInAtValueAnnotation_true() {
MockPropertySource mockPropertySource = new MockPropertySource("test");
mockPropertySource.setProperty("my.key", "${enigma}");
@SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().getPropertySources().addLast(mockPropertySource);
context.register(IgnoreUnresolvablePlaceholdersTrueConfig.class);
context.refresh();
IgnoreUnresolvablePlaceholdersTrueConfig config = context.getBean(IgnoreUnresolvablePlaceholdersTrueConfig.class);
assertThat(config.value).isEqualTo("${enigma}");
}
@Test
@SuppressWarnings("serial")
public void nestedUnresolvablePlaceholder() {
@@ -445,30 +402,4 @@ public class PropertySourcesPlaceholderConfigurerTests {
}
}
@Configuration
static class IgnoreUnresolvablePlaceholdersFalseConfig {
@Value("${my.key}")
String value;
@Bean
static PropertySourcesPlaceholderConfigurer pspc() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Configuration
static class IgnoreUnresolvablePlaceholdersTrueConfig {
@Value("${my.key}")
String value;
@Bean
static PropertySourcesPlaceholderConfigurer pspc() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
}
}
@@ -30,6 +30,7 @@ import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.util.StringValueResolver;
import org.springframework.validation.DataBinder;
import static org.assertj.core.api.Assertions.assertThat;
@@ -48,12 +49,15 @@ public class NumberFormattingTests {
@BeforeEach
public void setUp() {
DefaultConversionService.addDefaultConverters(conversionService);
conversionService.setEmbeddedValueResolver(strVal -> {
if ("${pattern}".equals(strVal)) {
return "#,##.00";
}
else {
return strVal;
conversionService.setEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
if ("${pattern}".equals(strVal)) {
return "#,##.00";
}
else {
return strVal;
}
}
});
conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -189,14 +189,24 @@ public class FormattingConversionServiceFactoryBeanTests {
public Printer<?> getPrinter(SpecialInt annotation, Class<?> fieldType) {
assertThat(annotation.value()).isEqualTo("aliased");
assertThat(annotation.alias()).isEqualTo("aliased");
return (object, locale) -> ":" + object.toString();
return new Printer<Integer>() {
@Override
public String print(Integer object, Locale locale) {
return ":" + object.toString();
}
};
}
@Override
public Parser<?> getParser(SpecialInt annotation, Class<?> fieldType) {
assertThat(annotation.value()).isEqualTo("aliased");
assertThat(annotation.alias()).isEqualTo("aliased");
return (text, locale) -> Integer.parseInt(text.substring(1));
return new Parser<Integer>() {
@Override
public Integer parse(String text, Locale locale) throws ParseException {
return Integer.parseInt(text.substring(1));
}
};
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 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.
@@ -39,6 +39,7 @@ import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.MBeanExporter;
import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssembler;
import org.springframework.util.SocketUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -176,8 +177,7 @@ class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
void lazyConnectionToRemote() throws Exception {
assumeTrue(runTests);
@SuppressWarnings("deprecation")
final int port = org.springframework.util.SocketUtils.findAvailableTcpPort();
final int port = SocketUtils.findAvailableTcpPort();
JMXServiceURL url = new JMXServiceURL("service:jmx:jmxmp://localhost:" + port);
JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,6 +28,8 @@ import javax.management.remote.JMXServiceURL;
import org.junit.jupiter.api.AfterEach;
import org.springframework.util.SocketUtils;
/**
* @author Rob Harrop
* @author Chris Beams
@@ -35,8 +37,7 @@ import org.junit.jupiter.api.AfterEach;
*/
class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTests {
@SuppressWarnings("deprecation")
private final int servicePort = org.springframework.util.SocketUtils.findAvailableTcpPort();
private final int servicePort = SocketUtils.findAvailableTcpPort();
private final String serviceUrl = "service:jmx:jmxmp://localhost:" + servicePort;
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.naming.ObjectNamingStrategy;
import org.springframework.jmx.support.ObjectNameManager;
import static org.assertj.core.api.Assertions.assertThat;
@@ -73,7 +74,12 @@ class MBeanExporterOperationsTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setNamingStrategy((managedBean, beanKey) -> objectNameTemplate);
exporter.setNamingStrategy(new ObjectNamingStrategy() {
@Override
public ObjectName getObjectName(Object managedBean, String beanKey) {
return objectNameTemplate;
}
});
JmxTestBean bean1 = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
@@ -95,7 +101,12 @@ class MBeanExporterOperationsTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setEnsureUniqueRuntimeObjectNames(false);
exporter.setNamingStrategy((managedBean, beanKey) -> objectNameTemplate);
exporter.setNamingStrategy(new ObjectNamingStrategy() {
@Override
public ObjectName getObjectName(Object managedBean, String beanKey) {
return objectNameTemplate;
}
});
JmxTestBean bean1 = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
@@ -90,8 +90,11 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
@Test
void testRegisterNotificationListenerForNonExistentMBean() throws Exception {
Map<String, NotificationListener> listeners = new HashMap<>();
NotificationListener dummyListener = (notification, handback) -> {
throw new UnsupportedOperationException();
NotificationListener dummyListener = new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
throw new UnsupportedOperationException();
}
};
// the MBean with the supplied object name does not exist...
listeners.put("spring:type=Test", dummyListener);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 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.
@@ -23,6 +23,7 @@ import javax.management.Attribute;
import javax.management.AttributeChangeNotification;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
@@ -116,7 +117,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(listenerBean);
exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
start(exporter);
// update the attribute
@@ -144,7 +145,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(listenerBean);
exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
start(exporter);
// update the attribute
@@ -167,20 +168,23 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
listenerBean.setNotificationFilter(notification -> {
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
return "Name".equals(changeNotification.getAttributeName());
}
else {
return false;
listenerBean.setNotificationFilter(new NotificationFilter() {
@Override
public boolean isNotificationEnabled(Notification notification) {
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
return "Name".equals(changeNotification.getAttributeName());
}
else {
return false;
}
}
});
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(listenerBean);
exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
start(exporter);
// update the attributes
@@ -83,9 +83,9 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
MBeanAttributeInfo[] inf = info.getAttributes();
assertThat(inf).as("Invalid number of Attributes returned").hasSize(getExpectedAttributeCount());
for (MBeanAttributeInfo element : inf) {
assertThat(element).as("MBeanAttributeInfo should not be null").isNotNull();
assertThat(element.getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull();
for (int x = 0; x < inf.length; x++) {
assertThat(inf[x]).as("MBeanAttributeInfo should not be null").isNotNull();
assertThat(inf[x].getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull();
}
}
@@ -95,9 +95,9 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
MBeanOperationInfo[] inf = info.getOperations();
assertThat(inf).as("Invalid number of Operations returned").hasSize(getExpectedOperationCount());
for (MBeanOperationInfo element : inf) {
assertThat(element).as("MBeanOperationInfo should not be null").isNotNull();
assertThat(element.getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull();
for (int x = 0; x < inf.length; x++) {
assertThat(inf[x]).as("MBeanOperationInfo should not be null").isNotNull();
assertThat(inf[x].getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import javax.management.remote.JMXServiceURL;
import org.junit.jupiter.api.Test;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.util.SocketUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -46,8 +47,7 @@ class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
private static final String OBJECT_NAME = "spring:type=connector,name=test";
@SuppressWarnings("deprecation")
private final String serviceUrl = "service:jmx:jmxmp://localhost:" + org.springframework.util.SocketUtils.findAvailableTcpPort();
private final String serviceUrl = "service:jmx:jmxmp://localhost:" + SocketUtils.findAvailableTcpPort();
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.util.SocketUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -38,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*/
class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTests {
@SuppressWarnings("deprecation")
private final String serviceUrl = "service:jmx:jmxmp://localhost:" + org.springframework.util.SocketUtils.findAvailableTcpPort();
private final String serviceUrl = "service:jmx:jmxmp://localhost:" + SocketUtils.findAvailableTcpPort();
@Test
@@ -27,6 +27,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
@@ -612,13 +613,16 @@ public class AsyncExecutionTests {
public DynamicAsyncInterfaceBean() {
ProxyFactory pf = new ProxyFactory(new HashMap<>());
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor((MethodInterceptor) invocation -> {
boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
assertThat(condition).isTrue();
if (Future.class.equals(invocation.getMethod().getReturnType())) {
return new AsyncResult<>(invocation.getArguments()[0].toString());
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
assertThat(condition).isTrue();
if (Future.class.equals(invocation.getMethod().getReturnType())) {
return new AsyncResult<>(invocation.getArguments()[0].toString());
}
return null;
}
return null;
});
advisor.addInterface(AsyncInterface.class);
pf.addAdvisor(advisor);
@@ -682,13 +686,16 @@ public class AsyncExecutionTests {
public DynamicAsyncMethodsInterfaceBean() {
ProxyFactory pf = new ProxyFactory(new HashMap<>());
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor((MethodInterceptor) invocation -> {
boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
assertThat(condition).isTrue();
if (Future.class.equals(invocation.getMethod().getReturnType())) {
return new AsyncResult<>(invocation.getArguments()[0].toString());
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
assertThat(condition).isTrue();
if (Future.class.equals(invocation.getMethod().getReturnType())) {
return new AsyncResult<>(invocation.getArguments()[0].toString());
}
return null;
}
return null;
});
advisor.addInterface(AsyncMethodsInterface.class);
pf.addAdvisor(advisor);
@@ -16,6 +16,7 @@
package org.springframework.scheduling.config;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;
@@ -58,7 +59,12 @@ public class ExecutorBeanDefinitionParserTests {
assertThat(getKeepAliveSeconds(executor)).isEqualTo(60);
assertThat(getAllowCoreThreadTimeOut(executor)).isFalse();
FutureTask<String> task = new FutureTask<>(() -> "foo");
FutureTask<String> task = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
return "foo";
}
});
executor.execute(task);
assertThat(task.get()).isEqualTo("foo");
}
@@ -16,13 +16,13 @@
package org.springframework.scheduling.support;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Year;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.Temporal;
import org.assertj.core.api.Condition;
@@ -30,7 +30,6 @@ import org.junit.jupiter.api.Test;
import static java.time.DayOfWeek.FRIDAY;
import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.DayOfWeek.THURSDAY;
import static java.time.DayOfWeek.TUESDAY;
@@ -47,8 +46,8 @@ class CronExpressionTests {
@Override
public boolean matches(Temporal value) {
DayOfWeek dayOfWeek = DayOfWeek.from(value);
return dayOfWeek != SATURDAY && dayOfWeek != SUNDAY;
int dayOfWeek = value.get(ChronoField.DAY_OF_WEEK);
return dayOfWeek != 6 && dayOfWeek != 7;
}
};
@@ -959,24 +958,6 @@ class CronExpressionTests {
assertThat(actual).isNotNull();
assertThat(actual).isEqualTo(expected);
assertThat(actual).is(weekday);
last = LocalDateTime.of(2022, 1, 1, 0, 0);
assertThat(last.getDayOfWeek()).isEqualTo(SATURDAY);
expected = LocalDateTime.of(2022, 1, 3, 0, 0);
assertThat(expected.getDayOfWeek()).isEqualTo(MONDAY);
actual = expression.next(last);
assertThat(actual).isNotNull();
assertThat(actual).isEqualTo(expected);
assertThat(actual).is(weekday);
last = LocalDateTime.of(2021, 8, 1, 0,0);
assertThat(last.getDayOfWeek()).isEqualTo(SUNDAY);
expected = LocalDateTime.of(2021, 8, 2, 0, 0);
assertThat(expected.getDayOfWeek()).isEqualTo(MONDAY);
actual = expression.next(last);
assertThat(actual).isNotNull();
assertThat(actual).isEqualTo(expected);
assertThat(actual).is(weekday);
}
@Test
@@ -1336,22 +1317,6 @@ class CronExpressionTests {
actual = cronExpression.next(last);
assertThat(actual).isNotNull();
assertThat(actual).isEqualTo(expected);
cronExpression = CronExpression.parse("0 5 0 * * *");
last = ZonedDateTime.parse("2021-03-28T01:00:00+01:00[Europe/Amsterdam]");
expected = ZonedDateTime.parse("2021-03-29T00:05+02:00[Europe/Amsterdam]");
actual = cronExpression.next(last);
assertThat(actual).isNotNull();
assertThat(actual).isEqualTo(expected);
cronExpression = CronExpression.parse("0 5 0 * * *");
last = ZonedDateTime.parse("2019-10-27T01:05+02:00[Europe/Amsterdam]");
expected = ZonedDateTime.parse("2019-10-28T00:05+01:00[Europe/Amsterdam]");
actual = cronExpression.next(last);
assertThat(actual).isNotNull();
assertThat(actual).isEqualTo(expected);
}
@Test
@@ -26,7 +26,7 @@ import org.codehaus.groovy.control.BytecodeProcessor;
*/
public class MyBytecodeProcessor implements BytecodeProcessor {
public final Set<String> processed = new HashSet<>();
public final Set<String> processed = new HashSet<String>();
@Override
public byte[] processBytecode(String name, byte[] original) {

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