diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java index 41a53a5e3aad..0ef3a1bc0013 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2002-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -317,15 +317,19 @@ public HandlerMethod createWithValidateFlags() { } /** - * If the provided instance contains a bean name rather than an object instance, - * the bean name is resolved before a {@link HandlerMethod} is created and returned. + * If the {@link #getBean() handler} is a bean name rather than the actual + * handler instance, resolve the bean name through Spring configuration + * (e.g. for prototype beans), and return a new {@link HandlerMethod} + * instance with the resolved handler. + *
If the {@link #getBean() handler} is not String, return the same instance.
*/
public HandlerMethod createWithResolvedBean() {
- Object handler = this.bean;
- if (this.bean instanceof String beanName) {
- Assert.state(this.beanFactory != null, "Cannot resolve bean name without BeanFactory");
- handler = this.beanFactory.getBean(beanName);
+ if (!(this.bean instanceof String beanName)) {
+ return this;
}
+
+ Assert.state(this.beanFactory != null, "Cannot resolve bean name without BeanFactory");
+ Object handler = this.beanFactory.getBean(beanName);
Assert.notNull(handler, "No handler instance");
return new HandlerMethod(this, handler, false);
}
diff --git a/spring-web/src/test/java/org/springframework/web/method/HandlerMethodTests.java b/spring-web/src/test/java/org/springframework/web/method/HandlerMethodTests.java
index 678b9587f658..660dfa06d6e2 100644
--- a/spring-web/src/test/java/org/springframework/web/method/HandlerMethodTests.java
+++ b/spring-web/src/test/java/org/springframework/web/method/HandlerMethodTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2024 the original author or authors.
+ * Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -72,6 +72,13 @@ void classLevelValidatedAnnotation() {
testValidateReturnValue(target, List.of("getPerson"), false);
}
+ @Test // gh-34277
+ void createWithResolvedBeanSameInstance() {
+ MyClass target = new MyClass();
+ HandlerMethod handlerMethod = getHandlerMethod(target, "addPerson");
+ assertThat(handlerMethod.createWithResolvedBean()).isSameAs(handlerMethod);
+ }
+
private static void testValidateArgs(Object target, List