Skip to content

Commit 3a39b7f

Browse files
committed
Support scoped @ControllerAdvice beans again
Spring Framework 5.2 introduced support for implementing the Ordered interface in a @ControllerAdvice bean. This support requires that @ControllerAdvice beans be eagerly resolved from the BeanFactory in order to invoke the getOrder() method defined in the Ordered interface. Unfortunately doing so resulted in a regression in that an attempt to eagerly resolve a scoped @ControllerAdvice bean throws a BeanCreationException due to the lack of an active scope (e.g., request or session scope). This commit fixes this regression by avoiding eager resolution of scoped @ControllerAdvice beans. As a direct consequence, the Ordered interface is not supported for scoped @ControllerAdvice beans. Closes gh-23985
1 parent f0b2f71 commit 3a39b7f

File tree

3 files changed

+125
-8
lines changed

3 files changed

+125
-8
lines changed

spring-web/src/main/java/org/springframework/web/bind/annotation/ControllerAdvice.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,12 @@
4242
* Note, however, that {@code @ControllerAdvice} beans that implement
4343
* {@link org.springframework.core.PriorityOrdered PriorityOrdered} are <em>not</em>
4444
* given priority over {@code @ControllerAdvice} beans that implement {@code Ordered}.
45-
* For handling exceptions, an {@code @ExceptionHandler} will be picked on the
46-
* first advice with a matching exception handler method. For model attributes
47-
* and {@code InitBinder} initialization, {@code @ModelAttribute} and
48-
* {@code @InitBinder} methods will also follow {@code @ControllerAdvice} order.
45+
* In addition, {@code Ordered} is not honored for scoped {@code @ControllerAdvice}
46+
* beans &mdash; for example if such a bean has been configured as a request-scoped
47+
* or session-scoped bean. For handling exceptions, an {@code @ExceptionHandler}
48+
* will be picked on the first advice with a matching exception handler method. For
49+
* model attributes and data binding initialization, {@code @ModelAttribute} and
50+
* {@code @InitBinder} methods will follow {@code @ControllerAdvice} order.
4951
*
5052
* <p>Note: For {@code @ExceptionHandler} methods, a root exception match will be
5153
* preferred to just matching a cause of the current exception, among the handler

spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.util.ArrayList;
2020
import java.util.List;
2121

22+
import org.springframework.aop.scope.ScopedProxyUtils;
2223
import org.springframework.beans.factory.BeanFactory;
2324
import org.springframework.beans.factory.BeanFactoryUtils;
2425
import org.springframework.context.ApplicationContext;
@@ -124,19 +125,42 @@ public ControllerAdviceBean(String beanName, BeanFactory beanFactory, @Nullable
124125
/**
125126
* Get the order value for the contained bean.
126127
* <p>As of Spring Framework 5.2, the order value is lazily retrieved using
127-
* the following algorithm and cached.
128+
* the following algorithm and cached. Note, however, that a
129+
* {@link ControllerAdvice @ControllerAdvice} bean that is configured as a
130+
* scoped bean &mdash; for example, as a request-scoped or session-scoped
131+
* bean &mdash; will not be eagerly resolved. Consequently, {@link Ordered} is
132+
* not honored for scoped {@code @ControllerAdvice} beans.
128133
* <ul>
129134
* <li>If the {@linkplain #resolveBean resolved bean} implements {@link Ordered},
130135
* use the value returned by {@link Ordered#getOrder()}.</li>
131-
* <li>Otherwise use the value returned by {@link OrderUtils#getOrder(Class, int)}
132-
* with {@link Ordered#LOWEST_PRECEDENCE} used as the default order value.</li>
136+
* <li>If the {@linkplain #getBeanType() bean type} is known, use the value returned
137+
* by {@link OrderUtils#getOrder(Class, int)} with {@link Ordered#LOWEST_PRECEDENCE}
138+
* used as the default order value.</li>
139+
* <li>Otherwise use {@link Ordered#LOWEST_PRECEDENCE} as the default, fallback
140+
* order value.</li>
133141
* </ul>
134142
* @see #resolveBean()
135143
*/
136144
@Override
137145
public int getOrder() {
138146
if (this.order == null) {
139-
Object resolvedBean = resolveBean();
147+
Object resolvedBean = null;
148+
if (this.beanOrName instanceof String) {
149+
String beanName = (String) this.beanOrName;
150+
String targetBeanName = ScopedProxyUtils.getTargetBeanName(beanName);
151+
boolean isScopedProxy = this.beanFactory.containsBean(targetBeanName);
152+
// Avoid eager @ControllerAdvice bean resolution for scoped proxies,
153+
// since attempting to do so during context initialization would result
154+
// in an exception due to the current absence of the scope. For example,
155+
// an HTTP request or session scope is not active during initialization.
156+
if (!isScopedProxy && !ScopedProxyUtils.isScopedTarget(beanName)) {
157+
resolvedBean = resolveBean();
158+
}
159+
}
160+
else {
161+
resolvedBean = resolveBean();
162+
}
163+
140164
if (resolvedBean instanceof Ordered) {
141165
this.order = ((Ordered) resolvedBean).getOrder();
142166
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
* Copyright 2002-2019 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.web.servlet.mvc.method.annotation;
18+
19+
import java.util.List;
20+
21+
import org.junit.jupiter.api.Test;
22+
23+
import org.springframework.context.annotation.Bean;
24+
import org.springframework.context.annotation.Configuration;
25+
import org.springframework.core.Ordered;
26+
import org.springframework.core.annotation.Order;
27+
import org.springframework.mock.web.test.MockServletContext;
28+
import org.springframework.web.bind.annotation.ControllerAdvice;
29+
import org.springframework.web.context.annotation.RequestScope;
30+
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
31+
import org.springframework.web.method.ControllerAdviceBean;
32+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
33+
34+
import static org.assertj.core.api.Assertions.assertThat;
35+
import static org.assertj.core.api.Assertions.assertThatCode;
36+
37+
/**
38+
* Integration tests for request-scoped {@link ControllerAdvice @ControllerAdvice} beans.
39+
*
40+
* @author Sam Brannen
41+
* @since 5.2.2
42+
*/
43+
class RequestScopedControllerAdviceIntegrationTests {
44+
45+
@Test // gh-23985
46+
@SuppressWarnings({ "rawtypes", "unchecked" })
47+
void loadContextWithRequestScopedControllerAdvice() {
48+
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
49+
context.setServletContext(new MockServletContext());
50+
context.register(Config.class);
51+
52+
assertThatCode(context::refresh).doesNotThrowAnyException();
53+
54+
// Until gh-24017 is fixed, we expect the RequestScopedControllerAdvice to show up twice.
55+
Class[] expectedTypes = { RequestScopedControllerAdvice.class, RequestScopedControllerAdvice.class };
56+
57+
List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(context);
58+
assertThat(adviceBeans)//
59+
.extracting(ControllerAdviceBean::getBeanType)//
60+
.containsExactly(expectedTypes);
61+
62+
assertThat(adviceBeans)//
63+
.extracting(ControllerAdviceBean::getOrder)//
64+
.containsExactly(42, 42);
65+
66+
context.close();
67+
}
68+
69+
70+
@Configuration
71+
@EnableWebMvc
72+
static class Config {
73+
74+
@Bean
75+
@RequestScope
76+
RequestScopedControllerAdvice requestScopedControllerAdvice() {
77+
return new RequestScopedControllerAdvice();
78+
}
79+
}
80+
81+
@ControllerAdvice
82+
@Order(42)
83+
static class RequestScopedControllerAdvice implements Ordered {
84+
85+
@Override
86+
public int getOrder() {
87+
return 99;
88+
}
89+
}
90+
91+
}

0 commit comments

Comments
 (0)