diff --git a/build.gradle b/build.gradle
index a86c93fcd8a6..c87a29205c59 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,12 +1,12 @@
plugins {
- id 'io.freefair.aspectj' version '8.13.1' apply false
- // kotlinVersion is managed in gradle.properties
- id 'org.jetbrains.kotlin.plugin.serialization' version "${kotlinVersion}" apply false
- id 'org.jetbrains.dokka'
id 'com.github.bjornvester.xjc' version '1.8.2' apply false
id 'com.gradleup.shadow' version "9.2.2" apply false
- id 'me.champeau.jmh' version '0.7.2' apply false
+ id 'io.freefair.aspectj' version '8.13.1' apply false
id 'io.spring.nullability' version '0.0.8' apply false
+ id 'me.champeau.jmh' version '0.7.2' apply false
+ id 'org.jetbrains.dokka'
+ id 'org.jetbrains.kotlin.plugin.serialization' version "${kotlinVersion}" apply false // kotlinVersion is managed in gradle.properties
+ id 'org.openrewrite.rewrite' version '7.20.0' apply false
}
ext {
@@ -16,6 +16,8 @@ ext {
description = "Spring Framework"
+apply from: "$rootDir/gradle/rewrite.gradle"
+
configure(allprojects) { project ->
apply plugin: "org.springframework.build.localdev"
group = "org.springframework"
diff --git a/gradle/rewrite.gradle b/gradle/rewrite.gradle
new file mode 100644
index 000000000000..af3ff64b98c8
--- /dev/null
+++ b/gradle/rewrite.gradle
@@ -0,0 +1,24 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+project.apply plugin: 'org.openrewrite.rewrite'
+
+rewrite {
+ activeRecipe('org.opensearch.openrewrite.SanityCheck')
+ setExportDatatables(true)
+ setFailOnDryRunResults(true)
+}
+
+dependencies {
+ rewrite(platform("org.openrewrite.recipe:rewrite-recipe-bom:3.18.0"))
+ rewrite("org.openrewrite.recipe:rewrite-migrate-java:3.21.1")
+ rewrite("org.openrewrite.recipe:rewrite-java-security:3.20.0")
+ rewrite("org.openrewrite.recipe:rewrite-rewrite:0.15.0")
+ rewrite("org.openrewrite.recipe:rewrite-static-analysis:2.21.0")
+ rewrite("org.openrewrite.recipe:rewrite-third-party:0.30.0")
+}
diff --git a/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java b/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java
index 73bce9a78b1a..ec3b6fadf02c 100644
--- a/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java
+++ b/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java
@@ -78,8 +78,8 @@ void afterAdviceIsInvokedLast(@Autowired Echo echo, @Autowired InvocationTrackin
static class Echo {
Object echo(Object obj) throws Exception {
- if (obj instanceof Exception) {
- throw (Exception) obj;
+ if (obj instanceof Exception exception) {
+ throw exception;
}
return obj;
}
diff --git a/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java b/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java
index b645ebd6423f..0304468e798e 100644
--- a/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java
+++ b/integration-tests/src/test/java/org/springframework/aop/framework/autoproxy/AspectJAutoProxyAdviceOrderIntegrationTests.java
@@ -133,8 +133,8 @@ Echo echo() {
static class Echo {
Object echo(Object obj) throws Exception {
- if (obj instanceof Exception) {
- throw (Exception) obj;
+ if (obj instanceof Exception exception) {
+ throw exception;
}
return obj;
}
diff --git a/rewrite.yml b/rewrite.yml
new file mode 100644
index 000000000000..a8e23cab0648
--- /dev/null
+++ b/rewrite.yml
@@ -0,0 +1,16 @@
+---
+type: specs.openrewrite.org/v1beta/recipe
+name: org.opensearch.openrewrite.SanityCheck
+displayName: Apply all Java & Gradle best practices
+description: Comprehensive code quality recipe combining modernization, security, and best practices.
+tags:
+ - java
+ - gradle
+ - static-analysis
+ - cleanup
+recipeList:
+ - org.openrewrite.gradle.EnableGradleBuildCache
+ - org.openrewrite.gradle.EnableGradleParallelExecution
+ - org.openrewrite.gradle.GradleBestPractices
+ - org.openrewrite.java.migrate.UpgradeToJava17
+---
diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java b/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java
index f91792694f06..c25e88f9b195 100644
--- a/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java
+++ b/spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java
@@ -18,6 +18,7 @@
import java.io.IOException;
import java.io.ObjectInputStream;
+import java.io.Serial;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@@ -68,7 +69,7 @@
public class AdvisedSupport extends ProxyConfig implements Advised {
/** use serialVersionUID from Spring 2.0 for interoperability. */
- private static final long serialVersionUID = 2651364800145442165L;
+ @Serial private static final long serialVersionUID = 2651364800145442165L;
private static final Advisor[] EMPTY_ADVISOR_ARRAY = new Advisor[0];
diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java b/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java
index b732c535ebdc..9b7bec30c539 100644
--- a/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java
+++ b/spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java
@@ -16,6 +16,7 @@
package org.springframework.aop.framework;
+import java.io.Serial;
import java.io.Serializable;
import java.lang.reflect.Proxy;
@@ -53,7 +54,7 @@ public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
*/
public static final DefaultAopProxyFactory INSTANCE = new DefaultAopProxyFactory();
- private static final long serialVersionUID = 7930414337282325166L;
+ @Serial private static final long serialVersionUID = 7930414337282325166L;
@Override
diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java b/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java
index b0016b00c039..548032cbd4db 100644
--- a/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java
+++ b/spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java
@@ -18,6 +18,7 @@
import java.io.IOException;
import java.io.ObjectInputStream;
+import java.io.Serial;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -70,7 +71,7 @@
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 5531744639992436476L;
+ @Serial private static final long serialVersionUID = 5531744639992436476L;
private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow";
diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java
index ca21266ba0ec..dfd102d220f2 100644
--- a/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java
+++ b/spring-aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java
@@ -16,6 +16,7 @@
package org.springframework.aop.framework;
+import java.io.Serial;
import java.io.Serializable;
import org.jspecify.annotations.Nullable;
@@ -33,7 +34,7 @@
public class ProxyConfig implements Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = -8409359707199703185L;
+ @Serial private static final long serialVersionUID = -8409359707199703185L;
private @Nullable Boolean proxyTargetClass;
diff --git a/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java b/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java
index 572c5e057e83..dd3fcbb2748e 100644
--- a/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java
+++ b/spring-aop/src/main/java/org/springframework/aop/support/ComposablePointcut.java
@@ -16,6 +16,7 @@
package org.springframework.aop.support;
+import java.io.Serial;
import java.io.Serializable;
import org.jspecify.annotations.Nullable;
@@ -45,7 +46,7 @@
public class ComposablePointcut implements Pointcut, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = -2743223737633663832L;
+ @Serial private static final long serialVersionUID = -2743223737633663832L;
@SuppressWarnings("serial")
private ClassFilter classFilter;
diff --git a/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java
index 912efdd9677f..be8faa86e2a7 100644
--- a/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java
+++ b/spring-aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java
@@ -16,6 +16,7 @@
package org.springframework.aop.target;
+import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;
@@ -53,7 +54,7 @@
public abstract class AbstractBeanFactoryBasedTargetSource implements TargetSource, BeanFactoryAware, Serializable {
/** use serialVersionUID from Spring 1.2.7 for interoperability. */
- private static final long serialVersionUID = -4721607536018568393L;
+ @Serial private static final long serialVersionUID = -4721607536018568393L;
/** Logger available to subclasses. */
diff --git a/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java
index 8460d4103046..338260c08d07 100644
--- a/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java
+++ b/spring-aop/src/main/java/org/springframework/aop/target/EmptyTargetSource.java
@@ -16,6 +16,7 @@
package org.springframework.aop.target;
+import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;
@@ -35,7 +36,7 @@
public final class EmptyTargetSource implements TargetSource, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 3680494563553489691L;
+ @Serial private static final long serialVersionUID = 3680494563553489691L;
//---------------------------------------------------------------------
diff --git a/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java
index 161bf92d8f8b..2a673ab5ae09 100644
--- a/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java
+++ b/spring-aop/src/main/java/org/springframework/aop/target/HotSwappableTargetSource.java
@@ -16,6 +16,7 @@
package org.springframework.aop.target;
+import java.io.Serial;
import java.io.Serializable;
import org.jspecify.annotations.Nullable;
@@ -40,7 +41,7 @@
public class HotSwappableTargetSource implements TargetSource, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 7497929212653839187L;
+ @Serial private static final long serialVersionUID = 7497929212653839187L;
/** The current target object. */
diff --git a/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java b/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java
index 5422682d91ed..99eadc218bb6 100644
--- a/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java
+++ b/spring-aop/src/main/java/org/springframework/aop/target/SingletonTargetSource.java
@@ -16,6 +16,7 @@
package org.springframework.aop.target;
+import java.io.Serial;
import java.io.Serializable;
import org.jspecify.annotations.Nullable;
@@ -40,7 +41,7 @@
public class SingletonTargetSource implements TargetSource, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 9031246629662423738L;
+ @Serial private static final long serialVersionUID = 9031246629662423738L;
/** Target cached and invoked using reflection. */
diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java
index 7fe2ec7e8859..6805b3786888 100644
--- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java
+++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java
@@ -54,7 +54,7 @@ void testManualProxyJavaWithStaticPointcut() {
TestService target = new TestServiceImpl();
LogUserAdvice logAdvice = new LogUserAdvice();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
- pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName()));
+ pointcut.setExpression("execution(* %s.TestService.*(..))".formatted(getClass().getName()));
testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl");
}
@@ -63,7 +63,7 @@ void testManualProxyJavaWithDynamicPointcut() {
TestService target = new TestServiceImpl();
LogUserAdvice logAdvice = new LogUserAdvice();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
- pointcut.setExpression(String.format("@within(%s.Log)", getClass().getName()));
+ pointcut.setExpression("@within(%s.Log)".formatted(getClass().getName()));
testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl");
}
@@ -72,7 +72,7 @@ void testManualProxyJavaWithDynamicPointcutAndProxyTargetClass() {
TestService target = new TestServiceImpl();
LogUserAdvice logAdvice = new LogUserAdvice();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
- pointcut.setExpression(String.format("@within(%s.Log)", getClass().getName()));
+ pointcut.setExpression("@within(%s.Log)".formatted(getClass().getName()));
testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl", true);
}
@@ -81,7 +81,7 @@ void testManualProxyJavaWithStaticPointcutAndTwoClassLoaders() throws Exception
LogUserAdvice logAdvice = new LogUserAdvice();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
- pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName()));
+ pointcut.setExpression("execution(* %s.TestService.*(..))".formatted(getClass().getName()));
// Test with default class loader first...
testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, new TestServiceImpl(), "TestServiceImpl");
diff --git a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
index a346ae41d38d..603d45274409 100644
--- a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
+++ b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
@@ -342,7 +342,7 @@ public int hashCode() {
@Override
public String toString() {
- return String.format("%s[name=%s, propertyType=%s, readMethod=%s, writeMethod=%s]",
+ return "%s[name=%s, propertyType=%s, readMethod=%s, writeMethod=%s]".formatted(
getClass().getSimpleName(), getName(), getPropertyType(), this.readMethod, this.writeMethod);
}
}
diff --git a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java
index de26e7b70671..0f1b5a93af91 100644
--- a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java
+++ b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/PathEditor.java
@@ -22,7 +22,6 @@
import java.net.URISyntaxException;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;
@@ -33,7 +32,7 @@
* Editor for {@code java.nio.file.Path}, to directly populate a Path
* property instead of using a String property as bridge.
*
- *
Based on {@link Paths#get(URI)}'s resolution algorithm, checking
+ *
Based on {@link Path#of(URI)}'s resolution algorithm, checking
* registered NIO file system providers, including the default file system
* for "file:..." paths. Also supports Spring-style URL notation: any fully
* qualified standard URL and Spring's special "classpath:" pseudo-URL, as
@@ -44,7 +43,7 @@
* @author Juergen Hoeller
* @since 4.3.2
* @see java.nio.file.Path
- * @see Paths#get(URI)
+ * @see Path#of(URI)
* @see ResourceEditor
* @see org.springframework.core.io.ResourceLoader
* @see FileEditor
@@ -83,7 +82,7 @@ public void setAsText(String text) throws IllegalArgumentException {
// No NIO candidate except for "C:" style drive letters
nioPathCandidate = (scheme.length() == 1);
// Let's try NIO file system providers via Paths.get(URI)
- setValue(Paths.get(uri).normalize());
+ setValue(Path.of(uri).normalize());
return;
}
}
@@ -104,7 +103,7 @@ public void setAsText(String text) throws IllegalArgumentException {
setValue(null);
}
else if (nioPathCandidate && (!resource.isFile() || !resource.exists())) {
- setValue(Paths.get(text).normalize());
+ setValue(Path.of(text).normalize());
}
else {
try {
diff --git a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java
index a221cdc8f852..d9342279a606 100644
--- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java
+++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java
@@ -577,8 +577,8 @@ void setStringPropertyWithCustomEditor() {
accessor.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
@Override
public void setValue(Object value) {
- if (value instanceof String[]) {
- setValue(StringUtils.arrayToDelimitedString(((String[]) value), "-"));
+ if (value instanceof String[] strings) {
+ setValue(StringUtils.arrayToDelimitedString(strings, "-"));
}
else {
super.setValue(value != null ? value : "");
@@ -929,8 +929,8 @@ void setPrimitiveArrayPropertyLargeMatchingWithSpecificEditor() {
accessor.registerCustomEditor(int.class, "array", new PropertyEditorSupport() {
@Override
public void setValue(Object value) {
- if (value instanceof Integer) {
- super.setValue((Integer) value + 1);
+ if (value instanceof Integer integer) {
+ super.setValue(integer + 1);
}
}
});
@@ -947,8 +947,8 @@ void setPrimitiveArrayPropertyLargeMatchingWithIndexSpecificEditor() {
accessor.registerCustomEditor(int.class, "array[1]", new PropertyEditorSupport() {
@Override
public void setValue(Object value) {
- if (value instanceof Integer) {
- super.setValue((Integer) value + 1);
+ if (value instanceof Integer integer) {
+ super.setValue(integer + 1);
}
}
});
diff --git a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java
index 260996841b3f..2910ac80d548 100644
--- a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java
+++ b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java
@@ -22,6 +22,7 @@
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ThreadLocalRandom;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -84,7 +85,7 @@ private static void performSet() {
for (Iterator> i = p.entrySet().iterator(); i.hasNext();) {
i.next();
- if (Math.random() > 0.9) {
+ if (ThreadLocalRandom.current().nextDouble() > 0.9) {
i.remove();
}
}
diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java
index 5d51fa814064..5dea77672b05 100644
--- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java
+++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java
@@ -150,16 +150,16 @@ public static class PostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
- if (bean instanceof ProtectedLifecycleBean) {
- ((ProtectedLifecycleBean) bean).postProcessBeforeInit();
+ if (bean instanceof ProtectedLifecycleBean lifecycleBean) {
+ lifecycleBean.postProcessBeforeInit();
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
- if (bean instanceof ProtectedLifecycleBean) {
- ((ProtectedLifecycleBean) bean).postProcessAfterInit();
+ if (bean instanceof ProtectedLifecycleBean lifecycleBean) {
+ lifecycleBean.postProcessAfterInit();
}
return bean;
}
diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java
index 4ee774e89d61..96665bcc4b14 100644
--- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java
+++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java
@@ -19,7 +19,6 @@
import java.beans.PropertyEditor;
import java.io.File;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
@@ -106,7 +105,7 @@ void testCurrentDirectory() {
Object value = pathEditor.getValue();
assertThat(value).isInstanceOf(Path.class);
Path path = (Path) value;
- assertThat(path).isEqualTo(Paths.get("."));
+ assertThat(path).isEqualTo(Path.of("."));
}
@Test
diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java
index 76d77e50f6a4..b42dcae7d946 100644
--- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java
+++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java
@@ -47,8 +47,9 @@ void oneProperty() {
@Test
void twoProperties() {
- String s = "foo=bar with whitespace\n" +
- "me=mi";
+ String s = """
+ foo=bar with whitespace
+ me=mi""";
PropertiesEditor pe= new PropertiesEditor();
pe.setAsText(s);
Properties p = (Properties) pe.getValue();
@@ -124,12 +125,14 @@ void ignoresCommentLinesAndEmptyLines() {
*/
@Test
void ignoresLeadingSpacesAndTabs() {
- String s = " #Ignore this comment\n" +
- "\t\tfoo=bar\n" +
- "\t#Another comment more junk \n" +
- " me=mi\n" +
- "x=x\n" +
- "\n";
+ String s = """
+ #Ignore this comment
+ foo=bar
+ #Another comment more junk\s
+ me=mi
+ x=x
+
+ """;
PropertiesEditor pe= new PropertiesEditor();
pe.setAsText(s);
Properties p = (Properties) pe.getValue();
diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java
index 2096f4d7c4f7..f717fe01cde3 100644
--- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java
+++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java
@@ -152,16 +152,16 @@ public static class PostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
- if (bean instanceof LifecycleBean) {
- ((LifecycleBean) bean).postProcessBeforeInit();
+ if (bean instanceof LifecycleBean lifecycleBean) {
+ lifecycleBean.postProcessBeforeInit();
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
- if (bean instanceof LifecycleBean) {
- ((LifecycleBean) bean).postProcessAfterInit();
+ if (bean instanceof LifecycleBean lifecycleBean) {
+ lifecycleBean.postProcessAfterInit();
}
return bean;
}
diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java
index 9d286c0fd2f8..d672e021f68a 100644
--- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java
+++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/SerializablePerson.java
@@ -57,8 +57,8 @@ public void setAge(int age) {
@Override
public Object echo(Object o) throws Throwable {
- if (o instanceof Throwable) {
- throw (Throwable) o;
+ if (o instanceof Throwable throwable) {
+ throw throwable;
}
return o;
}
diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java
index 76ea5a53fed5..793e4e747fa1 100644
--- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java
+++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/TestBean.java
@@ -488,8 +488,8 @@ public int hashCode() {
@Override
public int compareTo(Object other) {
- if (this.name != null && other instanceof TestBean) {
- return this.name.compareTo(((TestBean) other).getName());
+ if (this.name != null && other instanceof TestBean bean) {
+ return this.name.compareTo(bean.getName());
}
else {
return 1;
diff --git a/spring-context-indexer/spring-context-indexer.gradle b/spring-context-indexer/spring-context-indexer.gradle
index a0f311ee6d59..df154ab355de 100644
--- a/spring-context-indexer/spring-context-indexer.gradle
+++ b/spring-context-indexer/spring-context-indexer.gradle
@@ -1,6 +1,8 @@
description = "Spring Context Indexer"
dependencies {
+ compileOnly "jakarta.annotation:jakarta.annotation-api:1.3.5"
+
testImplementation(project(":spring-context"))
testImplementation("jakarta.annotation:jakarta.annotation-api")
testImplementation("jakarta.inject:jakarta.inject-api")
diff --git a/spring-context/src/main/java/org/springframework/cache/Cache.java b/spring-context/src/main/java/org/springframework/cache/Cache.java
index fb5c7bf07998..c267d21f1a1f 100644
--- a/spring-context/src/main/java/org/springframework/cache/Cache.java
+++ b/spring-context/src/main/java/org/springframework/cache/Cache.java
@@ -309,7 +309,7 @@ class ValueRetrievalException extends RuntimeException {
private final @Nullable Object key;
public ValueRetrievalException(@Nullable Object key, Callable> loader, @Nullable Throwable ex) {
- super(String.format("Value for key '%s' could not be loaded using '%s'", key, loader), ex);
+ super("Value for key '%s' could not be loaded using '%s'".formatted(key, loader), ex);
this.key = key;
}
diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java b/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java
index ff7cb2e59564..69df705f21b1 100644
--- a/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java
+++ b/spring-context/src/main/java/org/springframework/cache/interceptor/LoggingCacheErrorHandler.java
@@ -98,28 +98,28 @@ public LoggingCacheErrorHandler(String loggerName, boolean logStackTraces) {
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
logCacheError(
- () -> String.format("Cache '%s' failed to get entry with key '%s'", cache.getName(), key),
+ () -> "Cache '%s' failed to get entry with key '%s'".formatted(cache.getName(), key),
exception);
}
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, @Nullable Object value) {
logCacheError(
- () -> String.format("Cache '%s' failed to put entry with key '%s'", cache.getName(), key),
+ () -> "Cache '%s' failed to put entry with key '%s'".formatted(cache.getName(), key),
exception);
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
logCacheError(
- () -> String.format("Cache '%s' failed to evict entry with key '%s'", cache.getName(), key),
+ () -> "Cache '%s' failed to evict entry with key '%s'".formatted(cache.getName(), key),
exception);
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
logCacheError(
- () -> String.format("Cache '%s' failed to clear entries", cache.getName()),
+ () -> "Cache '%s' failed to clear entries".formatted(cache.getName()),
exception);
}
diff --git a/spring-context/src/main/java/org/springframework/cache/support/NullValue.java b/spring-context/src/main/java/org/springframework/cache/support/NullValue.java
index 6e20a95c77d2..be9bba997c9b 100644
--- a/spring-context/src/main/java/org/springframework/cache/support/NullValue.java
+++ b/spring-context/src/main/java/org/springframework/cache/support/NullValue.java
@@ -16,6 +16,7 @@
package org.springframework.cache.support;
+import java.io.Serial;
import java.io.Serializable;
import org.jspecify.annotations.Nullable;
@@ -38,7 +39,7 @@ public final class NullValue implements Serializable {
*/
public static final Object INSTANCE = new NullValue();
- private static final long serialVersionUID = 1L;
+ @Serial private static final long serialVersionUID = 1L;
private NullValue() {
diff --git a/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java b/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java
index f53c0eebfa87..5a0324b756ea 100644
--- a/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java
+++ b/spring-context/src/main/java/org/springframework/context/ApplicationEvent.java
@@ -16,6 +16,7 @@
package org.springframework.context;
+import java.io.Serial;
import java.time.Clock;
import java.util.EventObject;
@@ -31,7 +32,7 @@
public abstract class ApplicationEvent extends EventObject {
/** use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 7099057708183571937L;
+ @Serial private static final long serialVersionUID = 7099057708183571937L;
/** System time when the event happened. */
private final long timestamp;
diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java
index 6ae194adfb23..2345d13f06c7 100644
--- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java
+++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java
@@ -127,7 +127,7 @@ public Class> enhance(Class> configClass, @Nullable ClassLoader classLoader)
Enhancer enhancer = newEnhancer(configClass, classLoader);
Class> enhancedClass = createClass(enhancer, classLoaderMismatch);
if (logger.isTraceEnabled()) {
- logger.trace(String.format("Successfully enhanced %s; enhanced class name is: %s",
+ logger.trace("Successfully enhanced %s; enhanced class name is: %s".formatted(
configClass.getName(), enhancedClass.getName()));
}
return enhancedClass;
diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java
index c0c196aa5b1f..6548486071d6 100644
--- a/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java
+++ b/spring-context/src/main/java/org/springframework/context/annotation/ImportAwareAotBeanPostProcessor.java
@@ -72,7 +72,7 @@ private void setAnnotationMetadata(ImportAware instance) {
instance.setImportMetadata(metadataReader.getAnnotationMetadata());
}
catch (IOException ex) {
- throw new IllegalStateException(String.format("Failed to read metadata for '%s'", importingClass), ex);
+ throw new IllegalStateException("Failed to read metadata for '%s'".formatted(importingClass), ex);
}
}
diff --git a/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java b/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java
index ddfc13b5f38c..8ba11c69e01c 100644
--- a/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java
+++ b/spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java
@@ -157,7 +157,7 @@ private void writeNativeImageProperties(List args) {
}
StringBuilder sb = new StringBuilder();
sb.append("Args = ");
- sb.append(String.join(String.format(" \\%n"), args));
+ sb.append(String.join(" \\%n".formatted(), args));
Path file = getSettings().getResourceOutput().resolve("META-INF/native-image/" +
getSettings().getGroupId() + "/" + getSettings().getArtifactId() + "/native-image.properties");
try {
diff --git a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java
index e9c89586b088..b8d639054571 100644
--- a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java
+++ b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java
@@ -238,7 +238,7 @@ public Date parse(String text, Locale locale) throws ParseException {
}
if (this.source != null) {
ParseException parseException = new ParseException(
- String.format("Unable to parse date time value \"%s\" using configuration from %s", text, this.source),
+ "Unable to parse date time value \"%s\" using configuration from %s".formatted(text, this.source),
ex.getErrorOffset());
parseException.initCause(ex);
throw parseException;
diff --git a/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java b/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java
index 291f36cdb0df..34c6bc367563 100644
--- a/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java
+++ b/spring-context/src/main/java/org/springframework/format/datetime/standard/TemporalAccessorParser.java
@@ -115,7 +115,7 @@ public TemporalAccessor parse(String text, Locale locale) throws ParseException
}
if (this.source != null) {
throw new DateTimeParseException(
- String.format("Unable to parse date time value \"%s\" using configuration from %s", text, this.source),
+ "Unable to parse date time value \"%s\" using configuration from %s".formatted(text, this.source),
text, ex.getErrorIndex(), ex);
}
// else rethrow original exception
diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java
index c81c0687f4af..3cf1a78882fc 100644
--- a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java
+++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java
@@ -180,8 +180,7 @@ public static CronExpression parse(String expression) {
String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
if (fields.length != 6) {
- throw new IllegalArgumentException(String.format(
- "Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression));
+ throw new IllegalArgumentException("Cron expression must consist of 6 fields (found %d in \"%s\")".formatted(fields.length, expression));
}
try {
CronField seconds = CronField.parseSeconds(fields[0]);
diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java
index 83370a3e06ca..1cd4618e9880 100644
--- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java
+++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java
@@ -563,16 +563,16 @@ public static class PostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
- if (bean instanceof ProtectedLifecycleBean) {
- ((ProtectedLifecycleBean) bean).postProcessBeforeInit();
+ if (bean instanceof ProtectedLifecycleBean lifecycleBean) {
+ lifecycleBean.postProcessBeforeInit();
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
- if (bean instanceof ProtectedLifecycleBean) {
- ((ProtectedLifecycleBean) bean).postProcessAfterInit();
+ if (bean instanceof ProtectedLifecycleBean lifecycleBean) {
+ lifecycleBean.postProcessAfterInit();
}
return bean;
}
diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java
index d3d6bba777ca..f0fc8d56533f 100644
--- a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java
+++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java
@@ -59,7 +59,6 @@
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
-import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -77,9 +76,9 @@ class CustomNamespaceHandlerTests {
private static final String CLASSNAME = CLASS.getSimpleName();
private static final String FQ_PATH = "org/springframework/beans/factory/xml/support";
- private static final String NS_PROPS = format("%s/%s.properties", FQ_PATH, CLASSNAME);
- private static final String NS_XML = format("%s/%s-context.xml", FQ_PATH, CLASSNAME);
- private static final String TEST_XSD = format("%s/%s.xsd", FQ_PATH, CLASSNAME);
+ private static final String NS_PROPS = "%s/%s.properties".formatted(FQ_PATH, CLASSNAME);
+ private static final String NS_XML = "%s/%s-context.xml".formatted(FQ_PATH, CLASSNAME);
+ private static final String TEST_XSD = "%s/%s.xsd".formatted(FQ_PATH, CLASSNAME);
private GenericApplicationContext beanFactory;
diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java
index 7965dfd9a9c2..6d30fbd2c9dc 100644
--- a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java
+++ b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java
@@ -106,7 +106,7 @@ default String greet() {
default String greet(String name) {
setCacheMiss();
- return String.format("Hello %s!", name);
+ return "Hello %s!".formatted(name);
}
}
diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java
index 1864d8899e38..288ec534837c 100644
--- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java
+++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java
@@ -41,7 +41,6 @@
import org.springframework.core.ResolvableType;
import org.springframework.util.ObjectUtils;
-import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.util.StringUtils.uncapitalize;
@@ -137,7 +136,7 @@ void getBeanByTypeRaisesNoSuchBeanDefinitionException() {
Class> targetType = Pattern.class;
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean(targetType))
- .withMessageContaining(format("No qualifying bean of type '%s'", targetType.getName()));
+ .withMessageContaining("No qualifying bean of type '%s'".formatted(targetType.getName()));
}
@Test
diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
index 33b9c663d99a..03606c037b67 100644
--- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
+++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
@@ -532,24 +532,24 @@ public static class InitDestroyBeanPostProcessor implements DestructionAwareBean
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
- if (bean instanceof AnnotatedInitDestroyBean) {
- assertThat(((AnnotatedInitDestroyBean) bean).initCalled).isFalse();
+ if (bean instanceof AnnotatedInitDestroyBean destroyBean) {
+ assertThat(destroyBean.initCalled).isFalse();
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
- if (bean instanceof AnnotatedInitDestroyBean) {
- assertThat(((AnnotatedInitDestroyBean) bean).initCalled).isTrue();
+ if (bean instanceof AnnotatedInitDestroyBean destroyBean) {
+ assertThat(destroyBean.initCalled).isTrue();
}
return bean;
}
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
- if (bean instanceof AnnotatedInitDestroyBean) {
- assertThat(((AnnotatedInitDestroyBean) bean).destroyCalled).isFalse();
+ if (bean instanceof AnnotatedInitDestroyBean destroyBean) {
+ assertThat(destroyBean.destroyCalled).isFalse();
}
}
diff --git a/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java b/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java
index 10e56fe318a3..0634d9c8c463 100644
--- a/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java
+++ b/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java
@@ -196,7 +196,7 @@ public void dontExposeMe() {
}
- public interface FooMBean {
+ public public interface FooMBean {
String getName();
}
@@ -211,7 +211,7 @@ public String getName() {
}
- public interface FooMXBean {
+ public public interface FooMXBean {
String getName();
}
@@ -234,7 +234,7 @@ public static class Abc extends Bar {
}
- private interface JmxInterfaceMBean {
+ public interface JmxInterfaceMBean {
}
@@ -246,7 +246,7 @@ private interface SpecializedJmxInterface extends JmxInterface {
}
- private interface JmxClassMBean {
+ public interface JmxClassMBean {
}
diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java
index db2bbb79d59e..cc1a59fc120f 100644
--- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java
+++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java
@@ -290,8 +290,7 @@ public void run() {
}
if (expectedRunCount >= 0) {
if (actualRunCount.incrementAndGet() > expectedRunCount) {
- RuntimeException exception = new RuntimeException(String.format(
- "%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>",
+ RuntimeException exception = new RuntimeException("%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>".formatted(
getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get()));
this.exception.set(exception);
throw exception;
@@ -324,8 +323,7 @@ public String call() {
}
if (expectedRunCount >= 0) {
if (actualRunCount.incrementAndGet() > expectedRunCount) {
- throw new RuntimeException(String.format(
- "%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>",
+ throw new RuntimeException("%s failure for test '%s': expectedRunCount:<%d>, actualRunCount:<%d>".formatted(
getClass().getSimpleName(), this.testName, expectedRunCount, actualRunCount.get()));
}
}
diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java
index b56150a99605..784f5cb168d1 100644
--- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java
+++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java
@@ -52,8 +52,8 @@ protected AsyncTaskExecutor buildExecutor() {
@Override
void shutdownExecutor() {
for (Runnable task : concurrentExecutor.shutdownNow()) {
- if (task instanceof Future) {
- ((Future>) task).cancel(true);
+ if (task instanceof Future> future) {
+ future.cancel(true);
}
}
}
diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java
index 314a855a83d9..a03173c01e08 100644
--- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java
+++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskSchedulerTests.java
@@ -66,8 +66,8 @@ protected AsyncTaskExecutor buildExecutor() {
@Override
void shutdownExecutor() {
for (Runnable task : ((ExecutorService) scheduler.getConcurrentExecutor()).shutdownNow()) {
- if (task instanceof Future) {
- ((Future>) task).cancel(true);
+ if (task instanceof Future> future) {
+ future.cancel(true);
}
}
}
diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java
index bb28e0f3ec1e..b3b52c57adcd 100644
--- a/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java
+++ b/spring-context/src/test/java/org/springframework/scheduling/support/BitsCronFieldTests.java
@@ -114,7 +114,7 @@ void names() {
private static Condition set(int... indices) {
- return new Condition<>(String.format("set bits %s", Arrays.toString(indices))) {
+ return new Condition<>("set bits %s".formatted(Arrays.toString(indices))) {
@Override
public boolean matches(BitsCronField value) {
for (int index : indices) {
@@ -128,7 +128,7 @@ public boolean matches(BitsCronField value) {
}
private static Condition setRange(int min, int max) {
- return new Condition<>(String.format("set range %d-%d", min, max)) {
+ return new Condition<>("set range %d-%d".formatted(min, max)) {
@Override
public boolean matches(BitsCronField value) {
for (int i = min; i < max; i++) {
@@ -142,7 +142,7 @@ public boolean matches(BitsCronField value) {
}
private static Condition clear(int... indices) {
- return new Condition<>(String.format("clear bits %s", Arrays.toString(indices))) {
+ return new Condition<>("clear bits %s".formatted(Arrays.toString(indices))) {
@Override
public boolean matches(BitsCronField value) {
for (int index : indices) {
@@ -156,7 +156,7 @@ public boolean matches(BitsCronField value) {
}
private static Condition clearRange(int min, int max) {
- return new Condition<>(String.format("clear range %d-%d", min, max)) {
+ return new Condition<>("clear range %d-%d".formatted(min, max)) {
@Override
public boolean matches(BitsCronField value) {
for (int i = min; i < max; i++) {
diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java
index fe06d3fadc95..388b854e0715 100644
--- a/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java
+++ b/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java
@@ -231,12 +231,12 @@ private static TriggerContext context(@Nullable Object scheduled, @Nullable Obje
if (o == null) {
return null;
}
- if (o instanceof Instant) {
- return (Instant) o;
+ if (o instanceof Instant instant) {
+ return instant;
}
- if (o instanceof Number) {
+ if (o instanceof Number number) {
return Instant.now()
- .plus(NumberUtils.convertNumberToTargetClass((Number) o, Long.class),
+ .plus(NumberUtils.convertNumberToTargetClass(number, Long.class),
ChronoUnit.MILLIS);
}
throw new IllegalArgumentException(
diff --git a/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java b/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java
index 182f8ce85198..8f754e8af3d2 100644
--- a/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java
+++ b/spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java
@@ -204,11 +204,11 @@ public InitialContextFactory createInitialContextFactory(@Nullable Hashtable,?
Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (icf != null) {
Class> icfClass;
- if (icf instanceof Class) {
- icfClass = (Class>) icf;
+ if (icf instanceof Class> class1) {
+ icfClass = class1;
}
- else if (icf instanceof String) {
- icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader());
+ else if (icf instanceof String string) {
+ icfClass = ClassUtils.resolveClassName(string, getClass().getClassLoader());
}
else {
throw new IllegalArgumentException("Invalid value type for environment key [" +
diff --git a/spring-core-test/spring-core-test.gradle b/spring-core-test/spring-core-test.gradle
index a398ed30c3bf..f80bcf9b2d94 100644
--- a/spring-core-test/spring-core-test.gradle
+++ b/spring-core-test/spring-core-test.gradle
@@ -2,7 +2,8 @@ description = "Spring Core Test"
dependencies {
api(project(":spring-core"))
- optional("org.assertj:assertj-core")
+ compileOnly "jakarta.annotation:jakarta.annotation-api:1.3.5"
+ optional("org.assertj:assertj-core")
optional("org.junit.jupiter:junit-jupiter-api")
compileOnly("org.junit.jupiter:junit-jupiter-params") // Used in CompileWithForkedClassLoaderExtension Javadoc
compileOnly("org.junit.platform:junit-platform-launcher") // Used in CompileWithForkedClassLoaderExtension
diff --git a/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java b/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java
index 4345a09e5884..61b9ad6cb37f 100644
--- a/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java
+++ b/spring-core/src/jmh/java/org/springframework/core/codec/StringDecoderBenchmark.java
@@ -87,7 +87,7 @@ public void setup() {
""";
- int eventLength = String.format(eventTemplate, String.format("%05d", 1)).length();
+ int eventLength = eventTemplate.formatted("%05d".formatted(1)).length();
int eventCount = this.totalSize / eventLength;
DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
diff --git a/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java b/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java
index e7137dc1e3a3..72b61cb337f4 100644
--- a/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java
+++ b/spring-core/src/main/java/org/springframework/aot/generate/GeneratedClass.java
@@ -83,7 +83,7 @@ public void reserveMethodNames(String... reservedMethodNames) {
for (String reservedMethodName : reservedMethodNames) {
String generatedName = generateSequencedMethodName(MethodName.of(reservedMethodNames));
Assert.state(generatedName.equals(reservedMethodName),
- () -> String.format("Unable to reserve method name '%s'", reservedMethodName));
+ () -> "Unable to reserve method name '%s'".formatted(reservedMethodName));
}
}
diff --git a/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java b/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java
index b402d623a280..8fe866ecdd3c 100644
--- a/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java
+++ b/spring-core/src/main/java/org/springframework/aot/generate/ValueCodeGeneratorDelegates.java
@@ -238,7 +238,7 @@ private String escape(char ch) {
return escaped;
}
return (!Character.isISOControl(ch)) ? Character.toString(ch) :
- String.format("\\u%04x", (int) ch);
+ "\\u%04x".formatted((int) ch);
}
}
diff --git a/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java b/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java
index f581b752fae1..1bffbd1203cf 100644
--- a/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java
+++ b/spring-core/src/main/java/org/springframework/aot/nativex/BasicJsonWriter.java
@@ -164,7 +164,7 @@ private static String escape(CharSequence input) {
case '\t' -> "\\t";
default -> {
if (c <= 0x1F) {
- yield String.format("\\u%04x", c);
+ yield "\\u%04x".formatted(c);
}
else {
yield (char) c;
diff --git a/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java b/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java
index 50f054b9e2a6..8d0b6d7573de 100644
--- a/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java
+++ b/spring-core/src/main/java/org/springframework/asm/AnnotationWriter.java
@@ -194,63 +194,55 @@ public void visit(final String name, final Object value) {
if (useNamedValues) {
annotation.putShort(symbolTable.addConstantUtf8(name));
}
- if (value instanceof String) {
- annotation.put12('s', symbolTable.addConstantUtf8((String) value));
- } else if (value instanceof Byte) {
- annotation.put12('B', symbolTable.addConstantInteger(((Byte) value).byteValue()).index);
- } else if (value instanceof Boolean) {
- int booleanValue = ((Boolean) value).booleanValue() ? 1 : 0;
+ if (value instanceof String string) {
+ annotation.put12('s', symbolTable.addConstantUtf8(string));
+ } else if (value instanceof Byte byte1) {
+ annotation.put12('B', symbolTable.addConstantInteger(byte1.byteValue()).index);
+ } else if (value instanceof Boolean boolean1) {
+ int booleanValue = boolean1.booleanValue() ? 1 : 0;
annotation.put12('Z', symbolTable.addConstantInteger(booleanValue).index);
- } else if (value instanceof Character) {
- annotation.put12('C', symbolTable.addConstantInteger(((Character) value).charValue()).index);
- } else if (value instanceof Short) {
- annotation.put12('S', symbolTable.addConstantInteger(((Short) value).shortValue()).index);
- } else if (value instanceof Type) {
- annotation.put12('c', symbolTable.addConstantUtf8(((Type) value).getDescriptor()));
- } else if (value instanceof byte[]) {
- byte[] byteArray = (byte[]) value;
+ } else if (value instanceof Character character) {
+ annotation.put12('C', symbolTable.addConstantInteger(character.charValue()).index);
+ } else if (value instanceof Short short1) {
+ annotation.put12('S', symbolTable.addConstantInteger(short1.shortValue()).index);
+ } else if (value instanceof Type type) {
+ annotation.put12('c', symbolTable.addConstantUtf8(type.getDescriptor()));
+ } else if (value instanceof byte[] byteArray) {
annotation.put12('[', byteArray.length);
for (byte byteValue : byteArray) {
annotation.put12('B', symbolTable.addConstantInteger(byteValue).index);
}
- } else if (value instanceof boolean[]) {
- boolean[] booleanArray = (boolean[]) value;
+ } else if (value instanceof boolean[] booleanArray) {
annotation.put12('[', booleanArray.length);
for (boolean booleanValue : booleanArray) {
annotation.put12('Z', symbolTable.addConstantInteger(booleanValue ? 1 : 0).index);
}
- } else if (value instanceof short[]) {
- short[] shortArray = (short[]) value;
+ } else if (value instanceof short[] shortArray) {
annotation.put12('[', shortArray.length);
for (short shortValue : shortArray) {
annotation.put12('S', symbolTable.addConstantInteger(shortValue).index);
}
- } else if (value instanceof char[]) {
- char[] charArray = (char[]) value;
+ } else if (value instanceof char[] charArray) {
annotation.put12('[', charArray.length);
for (char charValue : charArray) {
annotation.put12('C', symbolTable.addConstantInteger(charValue).index);
}
- } else if (value instanceof int[]) {
- int[] intArray = (int[]) value;
+ } else if (value instanceof int[] intArray) {
annotation.put12('[', intArray.length);
for (int intValue : intArray) {
annotation.put12('I', symbolTable.addConstantInteger(intValue).index);
}
- } else if (value instanceof long[]) {
- long[] longArray = (long[]) value;
+ } else if (value instanceof long[] longArray) {
annotation.put12('[', longArray.length);
for (long longValue : longArray) {
annotation.put12('J', symbolTable.addConstantLong(longValue).index);
}
- } else if (value instanceof float[]) {
- float[] floatArray = (float[]) value;
+ } else if (value instanceof float[] floatArray) {
annotation.put12('[', floatArray.length);
for (float floatValue : floatArray) {
annotation.put12('F', symbolTable.addConstantFloat(floatValue).index);
}
- } else if (value instanceof double[]) {
- double[] doubleArray = (double[]) value;
+ } else if (value instanceof double[] doubleArray) {
annotation.put12('[', doubleArray.length);
for (double doubleValue : doubleArray) {
annotation.put12('D', symbolTable.addConstantDouble(doubleValue).index);
diff --git a/spring-core/src/main/java/org/springframework/asm/ClassReader.java b/spring-core/src/main/java/org/springframework/asm/ClassReader.java
index 5fc6edbe7e89..18b25d4a750c 100644
--- a/spring-core/src/main/java/org/springframework/asm/ClassReader.java
+++ b/spring-core/src/main/java/org/springframework/asm/ClassReader.java
@@ -1371,8 +1371,7 @@ private int readMethod(
// adapter between the reader and the writer. In this case, it might be possible to copy
// the method attributes directly into the writer. If so, return early without visiting
// the content of these attributes.
- if (methodVisitor instanceof MethodWriter) {
- MethodWriter methodWriter = (MethodWriter) methodVisitor;
+ if (methodVisitor instanceof MethodWriter methodWriter) {
if (methodWriter.canCopyMethodAttributes(
this,
synthetic,
diff --git a/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java b/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java
index bc6a96dede4c..195d57acab84 100644
--- a/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java
+++ b/spring-core/src/main/java/org/springframework/asm/ClassTooLargeException.java
@@ -27,6 +27,8 @@
// THE POSSIBILITY OF SUCH DAMAGE.
package org.springframework.asm;
+import java.io.Serial;
+
/**
* Exception thrown when the constant pool of a class produced by a {@link ClassWriter} is too
* large.
@@ -34,7 +36,7 @@
* @author Jason Zaugg
*/
public final class ClassTooLargeException extends IndexOutOfBoundsException {
- private static final long serialVersionUID = 160715609518896765L;
+ @Serial private static final long serialVersionUID = 160715609518896765L;
private final String className;
private final int constantPoolCount;
diff --git a/spring-core/src/main/java/org/springframework/asm/Frame.java b/spring-core/src/main/java/org/springframework/asm/Frame.java
index d70e18096ac2..39919217e92d 100644
--- a/spring-core/src/main/java/org/springframework/asm/Frame.java
+++ b/spring-core/src/main/java/org/springframework/asm/Frame.java
@@ -282,10 +282,10 @@ final void copyFrom(final Frame frame) {
* @return the abstract type corresponding to the given frame element type.
*/
static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) {
- if (type instanceof Integer) {
- return CONSTANT_KIND | ((Integer) type).intValue();
- } else if (type instanceof String) {
- String descriptor = Type.getObjectType((String) type).getDescriptor();
+ if (type instanceof Integer integer) {
+ return CONSTANT_KIND | integer.intValue();
+ } else if (type instanceof String string) {
+ String descriptor = Type.getObjectType(string).getDescriptor();
return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0);
} else {
Label label = (Label) type;
diff --git a/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java b/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java
index b41ec8b588ea..4cdd2fead518 100644
--- a/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java
+++ b/spring-core/src/main/java/org/springframework/asm/MethodTooLargeException.java
@@ -27,6 +27,8 @@
// THE POSSIBILITY OF SUCH DAMAGE.
package org.springframework.asm;
+import java.io.Serial;
+
/**
* Exception thrown when the Code attribute of a method produced by a {@link ClassWriter} is too
* large.
@@ -34,7 +36,7 @@
* @author Jason Zaugg
*/
public final class MethodTooLargeException extends IndexOutOfBoundsException {
- private static final long serialVersionUID = 6807380416709738314L;
+ @Serial private static final long serialVersionUID = 6807380416709738314L;
private final String className;
private final String methodName;
diff --git a/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java b/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java
index 7fc511d4e625..f15011d7c47b 100644
--- a/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java
+++ b/spring-core/src/main/java/org/springframework/asm/MethodVisitor.java
@@ -551,7 +551,7 @@ public void visitLabel(final Label label) {
public void visitLdcInsn(final Object value) {
if (api < Opcodes.ASM5
&& (value instanceof Handle
- || (value instanceof Type && ((Type) value).getSort() == Type.METHOD))) {
+ || (value instanceof Type type && type.getSort() == Type.METHOD))) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (api < Opcodes.ASM7 && value instanceof ConstantDynamic) {
diff --git a/spring-core/src/main/java/org/springframework/asm/MethodWriter.java b/spring-core/src/main/java/org/springframework/asm/MethodWriter.java
index 0e7eab3817d8..eb05fca78fae 100644
--- a/spring-core/src/main/java/org/springframework/asm/MethodWriter.java
+++ b/spring-core/src/main/java/org/springframework/asm/MethodWriter.java
@@ -1973,12 +1973,12 @@ private void putAbstractTypes(final int start, final int end) {
* a NEW instruction (for uninitialized types).
*/
private void putFrameType(final Object type) {
- if (type instanceof Integer) {
- stackMapTableEntries.putByte(((Integer) type).intValue());
- } else if (type instanceof String) {
+ if (type instanceof Integer integer) {
+ stackMapTableEntries.putByte(integer.intValue());
+ } else if (type instanceof String string) {
stackMapTableEntries
.putByte(Frame.ITEM_OBJECT)
- .putShort(symbolTable.addConstantClass((String) type).index);
+ .putShort(symbolTable.addConstantClass(string).index);
} else {
stackMapTableEntries.putByte(Frame.ITEM_UNINITIALIZED);
((Label) type).put(stackMapTableEntries);
diff --git a/spring-core/src/main/java/org/springframework/asm/SymbolTable.java b/spring-core/src/main/java/org/springframework/asm/SymbolTable.java
index 09e3d8e56444..0388580c4f52 100644
--- a/spring-core/src/main/java/org/springframework/asm/SymbolTable.java
+++ b/spring-core/src/main/java/org/springframework/asm/SymbolTable.java
@@ -480,26 +480,25 @@ private void add(final Entry entry) {
* @return a new or already existing Symbol with the given value.
*/
Symbol addConstant(final Object value) {
- if (value instanceof Integer) {
- return addConstantInteger(((Integer) value).intValue());
- } else if (value instanceof Byte) {
- return addConstantInteger(((Byte) value).intValue());
- } else if (value instanceof Character) {
- return addConstantInteger(((Character) value).charValue());
- } else if (value instanceof Short) {
- return addConstantInteger(((Short) value).intValue());
- } else if (value instanceof Boolean) {
- return addConstantInteger(((Boolean) value).booleanValue() ? 1 : 0);
- } else if (value instanceof Float) {
- return addConstantFloat(((Float) value).floatValue());
- } else if (value instanceof Long) {
- return addConstantLong(((Long) value).longValue());
- } else if (value instanceof Double) {
- return addConstantDouble(((Double) value).doubleValue());
- } else if (value instanceof String) {
- return addConstantString((String) value);
- } else if (value instanceof Type) {
- Type type = (Type) value;
+ if (value instanceof Integer integer) {
+ return addConstantInteger(integer.intValue());
+ } else if (value instanceof Byte byte1) {
+ return addConstantInteger(byte1.intValue());
+ } else if (value instanceof Character character) {
+ return addConstantInteger(character.charValue());
+ } else if (value instanceof Short short1) {
+ return addConstantInteger(short1.intValue());
+ } else if (value instanceof Boolean boolean1) {
+ return addConstantInteger(boolean1.booleanValue() ? 1 : 0);
+ } else if (value instanceof Float float1) {
+ return addConstantFloat(float1.floatValue());
+ } else if (value instanceof Long long1) {
+ return addConstantLong(long1.longValue());
+ } else if (value instanceof Double double1) {
+ return addConstantDouble(double1.doubleValue());
+ } else if (value instanceof String string) {
+ return addConstantString(string);
+ } else if (value instanceof Type type) {
int typeSort = type.getSort();
if (typeSort == Type.OBJECT) {
return addConstantClass(type.getInternalName());
@@ -508,16 +507,14 @@ Symbol addConstant(final Object value) {
} else { // type is a primitive or array type.
return addConstantClass(type.getDescriptor());
}
- } else if (value instanceof Handle) {
- Handle handle = (Handle) value;
+ } else if (value instanceof Handle handle) {
return addConstantMethodHandle(
handle.getTag(),
handle.getOwner(),
handle.getName(),
handle.getDesc(),
handle.isInterface());
- } else if (value instanceof ConstantDynamic) {
- ConstantDynamic constantDynamic = (ConstantDynamic) value;
+ } else if (value instanceof ConstantDynamic constantDynamic) {
return addConstantDynamic(
constantDynamic.getName(),
constantDynamic.getDescriptor(),
diff --git a/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java b/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java
index 17472414bfad..9e4117dbcc68 100644
--- a/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java
+++ b/spring-core/src/main/java/org/springframework/core/AttributeAccessor.java
@@ -77,7 +77,7 @@ default T computeAttribute(String name, Function computeFunction)
if (value == null) {
value = computeFunction.apply(name);
Assert.state(value != null,
- () -> String.format("Compute function must not return null for attribute named '%s'", name));
+ () -> "Compute function must not return null for attribute named '%s'".formatted(name));
setAttribute(name, value);
}
return (T) value;
diff --git a/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java b/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java
index b20a5008bcc1..c7a58ba5ba70 100644
--- a/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java
+++ b/spring-core/src/main/java/org/springframework/core/AttributeAccessorSupport.java
@@ -68,7 +68,7 @@ public T computeAttribute(String name, Function computeFunction)
Assert.notNull(computeFunction, "Compute function must not be null");
Object value = this.attributes.computeIfAbsent(name, computeFunction);
Assert.state(value != null,
- () -> String.format("Compute function must not return null for attribute named '%s'", name));
+ () -> "Compute function must not return null for attribute named '%s'".formatted(name));
return (T) value;
}
diff --git a/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java b/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java
index ee48c93138f0..6ce046358259 100644
--- a/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java
+++ b/spring-core/src/main/java/org/springframework/core/NestedCheckedException.java
@@ -16,6 +16,8 @@
package org.springframework.core;
+import java.io.Serial;
+
import org.jspecify.annotations.Nullable;
/**
@@ -34,7 +36,7 @@
public abstract class NestedCheckedException extends Exception {
/** Use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 7100714597678207546L;
+ @Serial private static final long serialVersionUID = 7100714597678207546L;
/**
diff --git a/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java b/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java
index 8b43cc80e663..45b89d844090 100644
--- a/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java
+++ b/spring-core/src/main/java/org/springframework/core/NestedRuntimeException.java
@@ -16,6 +16,8 @@
package org.springframework.core;
+import java.io.Serial;
+
import org.jspecify.annotations.Nullable;
/**
@@ -34,7 +36,7 @@
public abstract class NestedRuntimeException extends RuntimeException {
/** Use serialVersionUID from Spring 1.2 for interoperability. */
- private static final long serialVersionUID = 5439915454935047936L;
+ @Serial private static final long serialVersionUID = 5439915454935047936L;
/**
diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java
index a4be0aef1dd6..e368a9c6861a 100644
--- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java
+++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java
@@ -350,13 +350,11 @@ private T getRequiredAttribute(String attributeName, Class expectedType)
Assert.hasText(attributeName, "'attributeName' must not be null or empty");
Object value = get(attributeName);
if (value == null) {
- throw new IllegalArgumentException(String.format(
- "Attribute '%s' not found in attributes for annotation [%s]",
+ throw new IllegalArgumentException("Attribute '%s' not found in attributes for annotation [%s]".formatted(
attributeName, this.displayName));
}
if (value instanceof Throwable throwable) {
- throw new IllegalArgumentException(String.format(
- "Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]",
+ throw new IllegalArgumentException("Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]".formatted(
attributeName, this.displayName, value), throwable);
}
if (!expectedType.isInstance(value) && expectedType.isArray() &&
@@ -366,8 +364,7 @@ private T getRequiredAttribute(String attributeName, Class expectedType)
value = array;
}
if (!expectedType.isInstance(value)) {
- throw new IllegalArgumentException(String.format(
- "Attribute '%s' is of type %s, but %s was expected in attributes for annotation [%s]",
+ throw new IllegalArgumentException("Attribute '%s' is of type %s, but %s was expected in attributes for annotation [%s]".formatted(
attributeName, value.getClass().getSimpleName(), expectedType.getSimpleName(),
this.displayName));
}
diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java
index 51aaadbf99c2..0b08bc59e8f4 100644
--- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java
+++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationTypeMapping.java
@@ -152,12 +152,10 @@ private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean c
Method target = AttributeMethods.forAnnotationType(targetAnnotation).get(targetAttributeName);
if (target == null) {
if (targetAnnotation == this.annotationType) {
- throw new AnnotationConfigurationException(String.format(
- "@AliasFor declaration on %s declares an alias for '%s' which is not present.",
+ throw new AnnotationConfigurationException("@AliasFor declaration on %s declares an alias for '%s' which is not present.".formatted(
AttributeMethods.describe(attribute), targetAttributeName));
}
- throw new AnnotationConfigurationException(String.format(
- "%s is declared as an @AliasFor nonexistent %s.",
+ throw new AnnotationConfigurationException("%s is declared as an @AliasFor nonexistent %s.".formatted(
StringUtils.capitalize(AttributeMethods.describe(attribute)),
AttributeMethods.describe(targetAnnotation, targetAttributeName)));
}
@@ -168,8 +166,7 @@ private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean c
AttributeMethods.describe(attribute)));
}
if (!isCompatibleReturnType(attribute.getReturnType(), target.getReturnType())) {
- throw new AnnotationConfigurationException(String.format(
- "Misconfigured aliases: %s and %s must declare the same return type.",
+ throw new AnnotationConfigurationException("Misconfigured aliases: %s and %s must declare the same return type.".formatted(
AttributeMethods.describe(attribute),
AttributeMethods.describe(target)));
}
@@ -178,8 +175,7 @@ private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean c
if (targetAliasFor != null) {
Method mirror = resolveAliasTarget(target, targetAliasFor, false);
if (!mirror.equals(attribute)) {
- throw new AnnotationConfigurationException(String.format(
- "%s must be declared as an @AliasFor %s, not %s.",
+ throw new AnnotationConfigurationException("%s must be declared as an @AliasFor %s, not %s.".formatted(
StringUtils.capitalize(AttributeMethods.describe(target)),
AttributeMethods.describe(attribute), AttributeMethods.describe(mirror)));
}
@@ -320,8 +316,7 @@ private void validateAllAliasesClaimed() {
AliasFor aliasFor = AnnotationsScanner.getDeclaredAnnotation(attribute, AliasFor.class);
if (aliasFor != null && !this.claimedAliases.contains(attribute)) {
Method target = resolveAliasTarget(attribute, aliasFor);
- throw new AnnotationConfigurationException(String.format(
- "@AliasFor declaration on %s declares an alias for %s which is not meta-present.",
+ throw new AnnotationConfigurationException("@AliasFor declaration on %s declares an alias for %s which is not meta-present.".formatted(
AttributeMethods.describe(attribute), AttributeMethods.describe(target)));
}
}
@@ -334,13 +329,11 @@ private void validateMirrorSet(MirrorSet mirrorSet) {
Method mirrorAttribute = mirrorSet.get(i);
Object mirrorDefaultValue = mirrorAttribute.getDefaultValue();
if (firstDefaultValue == null || mirrorDefaultValue == null) {
- throw new AnnotationConfigurationException(String.format(
- "Misconfigured aliases: %s and %s must declare default values.",
+ throw new AnnotationConfigurationException("Misconfigured aliases: %s and %s must declare default values.".formatted(
AttributeMethods.describe(firstAttribute), AttributeMethods.describe(mirrorAttribute)));
}
if (!ObjectUtils.nullSafeEquals(firstDefaultValue, mirrorDefaultValue)) {
- throw new AnnotationConfigurationException(String.format(
- "Misconfigured aliases: %s and %s must declare the same default value.",
+ throw new AnnotationConfigurationException("Misconfigured aliases: %s and %s must declare the same default value.".formatted(
AttributeMethods.describe(firstAttribute), AttributeMethods.describe(mirrorAttribute)));
}
}
diff --git a/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java b/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java
index 8c8f5fc358bd..a92f01ad78dd 100644
--- a/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java
+++ b/spring-core/src/main/java/org/springframework/core/annotation/SynthesizedMergedAnnotationInvocationHandler.java
@@ -85,8 +85,7 @@ public Object invoke(Object proxy, Method method, Object[] args) {
if (ReflectionUtils.isEqualsMethod(method)) {
return annotationEquals(args[0]);
}
- throw new AnnotationConfigurationException(String.format(
- "Method [%s] is unsupported for synthesized annotation type [%s]", method, this.type));
+ throw new AnnotationConfigurationException("Method [%s] is unsupported for synthesized annotation type [%s]".formatted(method, this.type));
}
/**
@@ -174,7 +173,7 @@ private String toString(Object value) {
return '\'' + value.toString() + '\'';
}
if (value instanceof Byte) {
- return String.format("(byte) 0x%02X", value);
+ return "(byte) 0x%02X".formatted(value);
}
if (value instanceof Long longValue) {
return Long.toString(longValue) + 'L';
diff --git a/spring-core/src/main/java/org/springframework/core/io/PathResource.java b/spring-core/src/main/java/org/springframework/core/io/PathResource.java
index 9b8eaaefe83e..cf2b8ff5641c 100644
--- a/spring-core/src/main/java/org/springframework/core/io/PathResource.java
+++ b/spring-core/src/main/java/org/springframework/core/io/PathResource.java
@@ -30,7 +30,6 @@
import java.nio.file.NoSuchFileException;
import java.nio.file.OpenOption;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.jspecify.annotations.Nullable;
@@ -82,11 +81,11 @@ public PathResource(Path path) {
* via {@link #createRelative}, the relative path will be built underneath
* the given root: for example, Paths.get("C:/dir1/"), relative path "dir2" → "C:/dir1/dir2"!
* @param path a path
- * @see java.nio.file.Paths#get(String, String...)
+ * @see Path#of(String, String...)
*/
public PathResource(String path) {
Assert.notNull(path, "Path must not be null");
- this.path = Paths.get(path).normalize();
+ this.path = Path.of(path).normalize();
}
/**
@@ -95,11 +94,11 @@ public PathResource(String path) {
* via {@link #createRelative}, the relative path will be built underneath
* the given root: for example, Paths.get("C:/dir1/"), relative path "dir2" → "C:/dir1/dir2"!
* @param uri a path URI
- * @see java.nio.file.Paths#get(URI)
+ * @see Path#of(URI)
*/
public PathResource(URI uri) {
Assert.notNull(uri, "URI must not be null");
- this.path = Paths.get(uri).normalize();
+ this.path = Path.of(uri).normalize();
}
diff --git a/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java b/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java
index fe9469b878d6..12457ae40584 100644
--- a/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java
+++ b/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java
@@ -188,7 +188,7 @@ public DataBuffer capacity(int capacity) {
private void setCapacity(int newCapacity) {
if (newCapacity < 0) {
- throw new IllegalArgumentException(String.format("'newCapacity' %d must be 0 or higher", newCapacity));
+ throw new IllegalArgumentException("'newCapacity' %d must be 0 or higher".formatted(newCapacity));
}
int readPosition = readPosition();
int writePosition = writePosition();
@@ -497,7 +497,7 @@ public int hashCode() {
@Override
public String toString() {
- return String.format("DefaultDataBuffer (r: %d, w: %d, c: %d)",
+ return "DefaultDataBuffer (r: %d, w: %d, c: %d)".formatted(
this.readPosition, this.writePosition, this.capacity);
}
@@ -519,7 +519,7 @@ private void checkLength(int length) {
private void assertIndex(boolean expression, String format, Object... args) {
if (!expression) {
- String message = String.format(format, args);
+ String message = format.formatted(args);
throw new IndexOutOfBoundsException(message);
}
}
diff --git a/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java b/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java
index 5b2f30e0f6af..1631ca1dd52d 100644
--- a/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java
+++ b/spring-core/src/main/java/org/springframework/core/io/buffer/JettyDataBuffer.java
@@ -312,7 +312,7 @@ public int hashCode() {
@Override
public String toString() {
- return String.format("JettyDataBuffer (r: %d, w: %d, c: %d)",
+ return "JettyDataBuffer (r: %d, w: %d, c: %d)".formatted(
readPosition(), writePosition(), capacity());
}
diff --git a/spring-core/src/main/java/org/springframework/core/log/LogMessage.java b/spring-core/src/main/java/org/springframework/core/log/LogMessage.java
index 706c57bd4e3e..c526e7d85af7 100644
--- a/spring-core/src/main/java/org/springframework/core/log/LogMessage.java
+++ b/spring-core/src/main/java/org/springframework/core/log/LogMessage.java
@@ -89,7 +89,7 @@ public static LogMessage of(Supplier extends CharSequence> supplier) {
* Build a lazily formatted message from the given format string and argument.
* @param format the format string (following {@link String#format} rules)
* @param arg1 the argument (can be {@code null})
- * @see String#format(String, Object...)
+ * @see String#formatted(Object...)
*/
public static LogMessage format(String format, @Nullable Object arg1) {
return new FormatMessage1(format, arg1);
@@ -100,7 +100,7 @@ public static LogMessage format(String format, @Nullable Object arg1) {
* @param format the format string (following {@link String#format} rules)
* @param arg1 the first argument (can be {@code null})
* @param arg2 the second argument (can be {@code null})
- * @see String#format(String, Object...)
+ * @see String#formatted(Object...)
*/
public static LogMessage format(String format, @Nullable Object arg1, @Nullable Object arg2) {
return new FormatMessage2(format, arg1, arg2);
@@ -112,7 +112,7 @@ public static LogMessage format(String format, @Nullable Object arg1, @Nullable
* @param arg1 the first argument (can be {@code null})
* @param arg2 the second argument (can be {@code null})
* @param arg3 the third argument (can be {@code null})
- * @see String#format(String, Object...)
+ * @see String#formatted(Object...)
*/
public static LogMessage format(String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3) {
return new FormatMessage3(format, arg1, arg2, arg3);
@@ -125,7 +125,7 @@ public static LogMessage format(String format, @Nullable Object arg1, @Nullable
* @param arg2 the second argument (can be {@code null})
* @param arg3 the third argument (can be {@code null})
* @param arg4 the fourth argument (can be {@code null})
- * @see String#format(String, Object...)
+ * @see String#formatted(Object...)
*/
public static LogMessage format(String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3,
@Nullable Object arg4) {
@@ -140,7 +140,7 @@ public static LogMessage format(String format, @Nullable Object arg1, @Nullable
* @param format the format string (following {@link String#format} rules)
* @param args the varargs array (can be {@code null} and can contain {@code null}
* elements)
- * @see String#format(String, Object...)
+ * @see String#formatted(Object...)
*/
public static LogMessage format(String format, @Nullable Object... args) {
return new FormatMessageX(format, args);
@@ -185,7 +185,7 @@ private static final class FormatMessage1 extends FormatMessage {
@Override
protected String buildString() {
- return String.format(this.format, this.arg1);
+ return this.format.formatted(this.arg1);
}
}
@@ -204,7 +204,7 @@ private static final class FormatMessage2 extends FormatMessage {
@Override
String buildString() {
- return String.format(this.format, this.arg1, this.arg2);
+ return this.format.formatted(this.arg1, this.arg2);
}
}
@@ -226,7 +226,7 @@ private static final class FormatMessage3 extends FormatMessage {
@Override
String buildString() {
- return String.format(this.format, this.arg1, this.arg2, this.arg3);
+ return this.format.formatted(this.arg1, this.arg2, this.arg3);
}
}
@@ -252,7 +252,7 @@ private static final class FormatMessage4 extends FormatMessage {
@Override
String buildString() {
- return String.format(this.format, this.arg1, this.arg2, this.arg3, this.arg4);
+ return this.format.formatted(this.arg1, this.arg2, this.arg3, this.arg4);
}
}
@@ -268,7 +268,7 @@ private static final class FormatMessageX extends FormatMessage {
@Override
String buildString() {
- return String.format(this.format, this.args);
+ return this.format.formatted(this.args);
}
}
diff --git a/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java b/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java
index 3892df69aabc..dc4128cda346 100644
--- a/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java
+++ b/spring-core/src/main/java/org/springframework/core/style/SimpleValueStyler.java
@@ -135,7 +135,7 @@ private static String toSimpleMethodSignature(Method method) {
String parameterList = Arrays.stream(method.getParameterTypes())
.map(Class::getSimpleName)
.collect(Collectors.joining(", "));
- return String.format("%s(%s)", method.getName(), parameterList);
+ return "%s(%s)".formatted(method.getName(), parameterList);
}
}
diff --git a/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java b/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java
index 574b0eec83d8..ca6c4a6b8bee 100644
--- a/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java
+++ b/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java
@@ -16,6 +16,7 @@
package org.springframework.util;
+import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -37,7 +38,7 @@
*/
public class LinkedMultiValueMap extends MultiValueMapAdapter implements Serializable, Cloneable {
- private static final long serialVersionUID = 3801124242820219131L;
+ @Serial private static final long serialVersionUID = 3801124242820219131L;
/**
diff --git a/spring-core/src/main/java/org/springframework/util/MimeType.java b/spring-core/src/main/java/org/springframework/util/MimeType.java
index 7e02f5528da2..4348f0d1c8d2 100644
--- a/spring-core/src/main/java/org/springframework/util/MimeType.java
+++ b/spring-core/src/main/java/org/springframework/util/MimeType.java
@@ -18,6 +18,7 @@
import java.io.IOException;
import java.io.ObjectInputStream;
+import java.io.Serial;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.BitSet;
@@ -52,7 +53,7 @@
*/
public class MimeType implements Comparable, Serializable {
- private static final long serialVersionUID = 4085923477777865903L;
+ @Serial private static final long serialVersionUID = 4085923477777865903L;
protected static final String WILDCARD_TYPE = "*";
diff --git a/spring-core/src/main/java/org/springframework/util/StopWatch.java b/spring-core/src/main/java/org/springframework/util/StopWatch.java
index 50a3cb179a39..20cffb224ab3 100644
--- a/spring-core/src/main/java/org/springframework/util/StopWatch.java
+++ b/spring-core/src/main/java/org/springframework/util/StopWatch.java
@@ -332,7 +332,7 @@ public String prettyPrint(TimeUnit timeUnit) {
String line = "-".repeat(width) + "\n";
String unitName = timeUnit.name();
unitName = unitName.charAt(0) + unitName.substring(1).toLowerCase(Locale.ENGLISH);
- unitName = String.format("%-12s", unitName);
+ unitName = "%-12s".formatted(unitName);
sb.append(line);
sb.append(unitName).append(" % Task name\n");
sb.append(line);
@@ -345,9 +345,9 @@ public String prettyPrint(TimeUnit timeUnit) {
nf.setMaximumFractionDigits(10 - digits);
for (TaskInfo task : this.taskList) {
- sb.append(String.format("%-14s", (timeUnit == TimeUnit.NANOSECONDS ?
+ sb.append("%-14s".formatted((timeUnit == TimeUnit.NANOSECONDS ?
nf.format(task.getTimeNanos()) : nf.format(task.getTime(timeUnit)))));
- sb.append(String.format("%-8s",
+ sb.append("%-8s".formatted(
pf.format(task.getTimeSeconds() / getTotalTimeSeconds())));
sb.append(task.getTaskName()).append('\n');
}
diff --git a/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java b/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java
index 8db025670c2c..e107591db63a 100644
--- a/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java
+++ b/spring-core/src/main/java/org/springframework/util/UnmodifiableMultiValueMap.java
@@ -16,6 +16,7 @@
package org.springframework.util;
+import java.io.Serial;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
@@ -45,7 +46,7 @@
*/
final class UnmodifiableMultiValueMap implements MultiValueMap, Serializable {
- private static final long serialVersionUID = -8697084563854098920L;
+ @Serial private static final long serialVersionUID = -8697084563854098920L;
@SuppressWarnings("serial")
private final MultiValueMap delegate;
@@ -263,7 +264,7 @@ public void clear() {
private static class UnmodifiableEntrySet implements Set>>, Serializable {
- private static final long serialVersionUID = 2407578793783925203L;
+ @Serial private static final long serialVersionUID = 2407578793783925203L;
@SuppressWarnings("serial")
private final Set>> delegate;
@@ -512,7 +513,7 @@ public String toString() {
private static class UnmodifiableValueCollection implements Collection>, Serializable {
- private static final long serialVersionUID = 5518377583904339588L;
+ @Serial private static final long serialVersionUID = 5518377583904339588L;
@SuppressWarnings("serial")
private final Collection> delegate;
diff --git a/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java b/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java
index c641f2887e0e..1c820eb2e908 100644
--- a/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java
+++ b/spring-core/src/main/java/org/springframework/util/backoff/ExponentialBackOff.java
@@ -17,6 +17,7 @@
package org.springframework.util.backoff;
import java.util.StringJoiner;
+import java.util.concurrent.ThreadLocalRandom;
import org.springframework.util.Assert;
@@ -308,7 +309,7 @@ private long applyJitter(long interval) {
long applicableJitter = jitter * (interval / initialInterval);
long min = Math.max(interval - applicableJitter, initialInterval);
long max = Math.min(interval + applicableJitter, getMaxInterval());
- return min + (long) (Math.random() * (max - min));
+ return min + (long) (ThreadLocalRandom.current().nextDouble() * (max - min));
}
return interval;
}
diff --git a/spring-core/src/main/java/org/springframework/util/unit/DataSize.java b/spring-core/src/main/java/org/springframework/util/unit/DataSize.java
index 41180643202c..2912360011a4 100644
--- a/spring-core/src/main/java/org/springframework/util/unit/DataSize.java
+++ b/spring-core/src/main/java/org/springframework/util/unit/DataSize.java
@@ -252,7 +252,7 @@ public int compareTo(DataSize other) {
@Override
public String toString() {
- return String.format("%dB", this.bytes);
+ return "%dB".formatted(this.bytes);
}
diff --git a/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java
index 824998b5a0b9..0d186c21bb0d 100644
--- a/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java
+++ b/spring-core/src/test/java/org/springframework/core/codec/CharBufferDecoderTests.java
@@ -70,7 +70,7 @@ protected void decode() {
CharBuffer u = charBuffer("ü");
CharBuffer e = charBuffer("é");
CharBuffer o = charBuffer("ø");
- String s = String.format("%s\n%s\n%s", u, e, o);
+ String s = "%s\n%s\n%s".formatted(u, e, o);
Flux input = toDataBuffers(s, 1, UTF_8);
testDecodeAll(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null);
@@ -81,7 +81,7 @@ void decodeMultibyteCharacterUtf16() {
CharBuffer u = charBuffer("ü");
CharBuffer e = charBuffer("é");
CharBuffer o = charBuffer("ø");
- String s = String.format("%s\n%s\n%s", u, e, o);
+ String s = "%s\n%s\n%s".formatted(u, e, o);
Flux source = toDataBuffers(s, 2, UTF_16BE);
MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain;charset=utf-16be");
diff --git a/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java
index 688420275311..3e2649998d6b 100644
--- a/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java
+++ b/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java
@@ -82,7 +82,7 @@ void calculateCapacity() {
.forEach(charset -> {
int capacity = this.encoder.calculateCapacity(sequence, charset);
int length = sequence.length();
- assertThat(capacity).as(String.format("%s has capacity %d; length %d", charset, capacity, length))
+ assertThat(capacity).as("%s has capacity %d; length %d".formatted(charset, capacity, length))
.isGreaterThanOrEqualTo(length);
});
}
diff --git a/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java
index 8caad8611450..df5cac21d95a 100644
--- a/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java
+++ b/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java
@@ -73,7 +73,7 @@ protected void decode() {
String u = "ü";
String e = "é";
String o = "ø";
- String s = String.format("%s\n%s\n%s", u, e, o);
+ String s = "%s\n%s\n%s".formatted(u, e, o);
Flux input = toDataBuffers(s, 1, UTF_8);
testDecodeAll(input, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), null, null);
@@ -92,7 +92,7 @@ void decodeMultibyteCharacterUtf16() {
String u = "ü";
String e = "é";
String o = "ø";
- String s = String.format("%s\n%s\n%s", u, e, o);
+ String s = "%s\n%s\n%s".formatted(u, e, o);
Flux source = toDataBuffers(s, 2, UTF_16BE);
MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain;charset=utf-16be");
diff --git a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java
index 5823195032f5..209b8edab361 100644
--- a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java
+++ b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java
@@ -27,7 +27,6 @@
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -88,7 +87,7 @@ void nullUri() {
@Test
void createFromPath() {
- Path path = Paths.get(TEST_FILE);
+ Path path = Path.of(TEST_FILE);
PathResource resource = new PathResource(path);
assertThat(resource.getPath()).isEqualTo(TEST_FILE);
}
diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java
index 9385a210f99a..dce26e6f108a 100644
--- a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java
+++ b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java
@@ -32,7 +32,6 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
@@ -132,7 +131,7 @@ void resourceCreateRelativeUnknown(Resource resource) throws Exception {
private static Stream resource() throws URISyntaxException {
URL resourceClass = ResourceTests.class.getResource("ResourceTests.class");
- Path resourceClassFilePath = Paths.get(resourceClass.toURI());
+ Path resourceClassFilePath = Path.of(resourceClass.toURI());
return Stream.of(
argumentSet("ClassPathResource", new ClassPathResource("org/springframework/core/io/ResourceTests.class")),
argumentSet("ClassPathResource with ClassLoader", new ClassPathResource("org/springframework/core/io/ResourceTests.class", ResourceTests.class.getClassLoader())),
@@ -252,7 +251,7 @@ void sameResourceFromFileIsEqual() {
@Test
void sameResourceFromFilePathIsEqual() throws Exception {
- Path filePath = Paths.get(getClass().getResource("ResourceTests.class").toURI());
+ Path filePath = Path.of(getClass().getResource("ResourceTests.class").toURI());
Resource resource = new FileSystemResource(filePath);
assertThat(resource).isEqualTo(new FileSystemResource(filePath));
}
diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java
index 00d95af03a18..c397d75b4ea1 100644
--- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java
+++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java
@@ -31,7 +31,6 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.ArrayList;
@@ -99,7 +98,7 @@ void readByteChannel(DataBufferFactory bufferFactory) throws Exception {
URI uri = this.resource.getURI();
Flux result =
- DataBufferUtils.readByteChannel(() -> FileChannel.open(Paths.get(uri), StandardOpenOption.READ),
+ DataBufferUtils.readByteChannel(() -> FileChannel.open(Path.of(uri), StandardOpenOption.READ),
super.bufferFactory, 3);
verifyReadData(result);
@@ -134,7 +133,7 @@ void readByteChannelCancel(DataBufferFactory bufferFactory) throws Exception {
URI uri = this.resource.getURI();
Flux result =
- DataBufferUtils.readByteChannel(() -> FileChannel.open(Paths.get(uri), StandardOpenOption.READ),
+ DataBufferUtils.readByteChannel(() -> FileChannel.open(Path.of(uri), StandardOpenOption.READ),
super.bufferFactory, 3);
StepVerifier.create(result)
@@ -149,7 +148,7 @@ void readAsynchronousFileChannel(DataBufferFactory bufferFactory) throws Excepti
URI uri = this.resource.getURI();
Flux flux = DataBufferUtils.readAsynchronousFileChannel(
- () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ),
+ () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ),
super.bufferFactory, 3);
verifyReadData(flux);
@@ -161,7 +160,7 @@ void readAsynchronousFileChannelPosition(DataBufferFactory bufferFactory) throws
URI uri = this.resource.getURI();
Flux flux = DataBufferUtils.readAsynchronousFileChannel(
- () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ),
+ () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ),
9, super.bufferFactory, 3);
StepVerifier.create(flux)
@@ -207,7 +206,7 @@ void readAsynchronousFileChannelCancel(DataBufferFactory bufferFactory) throws E
URI uri = this.resource.getURI();
Flux flux = DataBufferUtils.readAsynchronousFileChannel(
- () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ),
+ () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ),
super.bufferFactory, 3);
StepVerifier.create(flux)
@@ -222,7 +221,7 @@ void readAsynchronousFileChannelCancelWithoutDemand(DataBufferFactory bufferFact
URI uri = this.resource.getURI();
Flux flux = DataBufferUtils.readAsynchronousFileChannel(
- () -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ),
+ () -> AsynchronousFileChannel.open(Path.of(uri), StandardOpenOption.READ),
super.bufferFactory, 3);
BaseSubscriber subscriber = new ZeroDemandSubscriber();
@@ -891,7 +890,7 @@ void inputStreamSubscriberClose(DataBufferFactory bufferFactory) throws Interrup
void readAndWriteByteChannel(DataBufferFactory bufferFactory) throws Exception {
super.bufferFactory = bufferFactory;
- Path source = Paths.get(
+ Path source = Path.of(
DataBufferUtilsTests.class.getResource("DataBufferUtilsTests.txt").toURI());
Flux sourceFlux =
DataBufferUtils
@@ -925,7 +924,7 @@ void readAndWriteByteChannel(DataBufferFactory bufferFactory) throws Exception {
void readAndWriteAsynchronousFileChannel(DataBufferFactory bufferFactory) throws Exception {
super.bufferFactory = bufferFactory;
- Path source = Paths.get(
+ Path source = Path.of(
DataBufferUtilsTests.class.getResource("DataBufferUtilsTests.txt").toURI());
Flux sourceFlux = DataBufferUtils.readAsynchronousFileChannel(
() -> AsynchronousFileChannel.open(source, StandardOpenOption.READ),
@@ -1283,7 +1282,7 @@ void matcher3(DataBufferFactory bufferFactory) {
@ParameterizedDataBufferAllocatingTest
void propagateContextByteChannel(DataBufferFactory bufferFactory) throws IOException {
- Path path = Paths.get(this.resource.getURI());
+ Path path = Path.of(this.resource.getURI());
try (SeekableByteChannel out = Files.newByteChannel(this.tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
Flux result = DataBufferUtils.read(path, bufferFactory, 1024, StandardOpenOption.READ)
.transformDeferredContextual((f, ctx) -> {
@@ -1307,7 +1306,7 @@ void propagateContextByteChannel(DataBufferFactory bufferFactory) throws IOExcep
@ParameterizedDataBufferAllocatingTest
void propagateContextAsynchronousFileChannel(DataBufferFactory bufferFactory) throws IOException {
- Path path = Paths.get(this.resource.getURI());
+ Path path = Path.of(this.resource.getURI());
try (AsynchronousFileChannel out = AsynchronousFileChannel.open(this.tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
Flux result = DataBufferUtils.read(path, bufferFactory, 1024, StandardOpenOption.READ)
.transformDeferredContextual((f, ctx) -> {
@@ -1331,7 +1330,7 @@ void propagateContextAsynchronousFileChannel(DataBufferFactory bufferFactory) th
@ParameterizedDataBufferAllocatingTest
void propagateContextPath(DataBufferFactory bufferFactory) throws IOException {
- Path path = Paths.get(this.resource.getURI());
+ Path path = Path.of(this.resource.getURI());
Path out = Files.createTempFile("data-buffer-utils-tests", ".tmp");
Flux result = DataBufferUtils.read(path, bufferFactory, 1024, StandardOpenOption.READ)
diff --git a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java
index e0390b6c7b03..78005547bc83 100644
--- a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java
+++ b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java
@@ -30,7 +30,6 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
@@ -118,8 +117,8 @@ void classpathStarWithPatternOnFileSystem() {
@Test // gh-31111
void usingFileProtocolWithWildcardInPatternAndNonexistentRootPath() throws IOException {
- Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath();
- String pattern = String.format("file:%s/example/bogus/**", testResourcesDir);
+ Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath();
+ String pattern = "file:%s/example/bogus/**".formatted(testResourcesDir);
assertThat(resolver.getResources(pattern)).isEmpty();
// When the log level for the resolver is set to at least INFO, we should see
// a log entry similar to the following.
@@ -131,7 +130,7 @@ void usingFileProtocolWithWildcardInPatternAndNonexistentRootPath() throws IOExc
@Test
void encodedHashtagInPath() throws IOException {
- Path rootDir = Paths.get("src/test/resources/custom%23root").toAbsolutePath();
+ Path rootDir = Path.of("src/test/resources/custom%23root").toAbsolutePath();
URL root = new URL("file:" + rootDir + "/");
resolver = new PathMatchingResourcePatternResolver(new DefaultResourceLoader(new URLClassLoader(new URL[] {root})));
resolver.setUseCaches(false);
@@ -164,8 +163,8 @@ void usingClasspathStarProtocolWithWildcardInPatternAndNotEndingInSlash() throws
@Test
void usingFileProtocolWithWildcardInPatternAndNotEndingInSlash() throws Exception {
- Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath();
- String pattern = String.format("file:%s/org/springframework/core/io/sup*", testResourcesDir);
+ Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath();
+ String pattern = "file:%s/org/springframework/core/io/sup*".formatted(testResourcesDir);
String pathPrefix = ".+org/springframework/core/io/";
List actualSubPaths = getSubPathsIgnoringClassFilesEtc(pattern, pathPrefix);
@@ -195,8 +194,8 @@ void usingClasspathStarProtocolWithWildcardInPatternAndEndingInSlash() throws Ex
@Test
void usingFileProtocolWithWildcardInPatternAndEndingInSlash() throws Exception {
- Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath();
- String pattern = String.format("file:%s/org/springframework/core/io/sup*/", testResourcesDir);
+ Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath();
+ String pattern = "file:%s/org/springframework/core/io/sup*/".formatted(testResourcesDir);
String pathPrefix = ".+org/springframework/core/io/";
List actualSubPaths = getSubPathsIgnoringClassFilesEtc(pattern, pathPrefix);
@@ -229,8 +228,8 @@ private List getSubPathsIgnoringClassFilesEtc(String pattern, String pat
@Test
void usingFileProtocolWithoutWildcardInPatternAndEndingInSlashStarStar() {
- Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath();
- String pattern = String.format("file:%s/scanned-resources/**", testResourcesDir);
+ Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath();
+ String pattern = "file:%s/scanned-resources/**".formatted(testResourcesDir);
String pathPrefix = ".+?resources/";
// We do NOT find "scanned-resources" if the pattern ENDS with "/**" AND does NOT otherwise contain a wildcard.
@@ -241,8 +240,8 @@ void usingFileProtocolWithoutWildcardInPatternAndEndingInSlashStarStar() {
@Test
void usingFileProtocolWithWildcardInPatternAndEndingInSlashStarStar() {
- Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath();
- String pattern = String.format("file:%s/scanned*resources/**", testResourcesDir);
+ Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath();
+ String pattern = "file:%s/scanned*resources/**".formatted(testResourcesDir);
String pathPrefix = ".+?resources/";
// We DO find "scanned-resources" if the pattern ENDS with "/**" AND DOES otherwise contain a wildcard.
@@ -253,7 +252,7 @@ void usingFileProtocolWithWildcardInPatternAndEndingInSlashStarStar() {
@Test
void usingFileProtocolAndAssertingUrlAndUriSyntax() throws Exception {
- Path testResourcesDir = Paths.get("src/test/resources").toAbsolutePath();
+ Path testResourcesDir = Path.of("src/test/resources").toAbsolutePath();
String pattern = "file:%s/scanned-resources/**/resource#test1.txt".formatted(testResourcesDir);
Resource[] resources = resolver.getResources(pattern);
assertThat(resources).hasSize(1);
diff --git a/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java
index 016b00d374fe..64b6f5aa2688 100644
--- a/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java
+++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java
@@ -68,8 +68,8 @@ public void absquatulate() {
@Override
public int compareTo(Object o) {
- if (this.name != null && o instanceof TestObject) {
- return this.name.compareTo(((TestObject) o).getName());
+ if (this.name != null && o instanceof TestObject object) {
+ return this.name.compareTo(object.getName());
}
else {
return 1;
diff --git a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java
index 41eee5a7d911..e518e36ec02e 100644
--- a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java
+++ b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java
@@ -83,8 +83,8 @@ private void doTestWithElementFactory(AutoPopulatingList