Document ControllerAdviceBean as internal usage

This commit documents `ControllerAdviceBean` as internal usage, as it is
not meant for application to manually create controller advice bean
instances.

This also refactors the existing partial implementation of the support
for creating controller advice beans "programmatically".

Closes gh-32776
This commit is contained in:
Brian Clozel
2024-07-26 17:52:20 +02:00
parent 94e2bef9a3
commit b888f362e5
3 changed files with 138 additions and 175 deletions

View File

@@ -23,7 +23,9 @@ import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
@@ -109,7 +111,7 @@ class RequestResponseBodyAdviceChainTests {
@Test
void controllerAdvice() {
Object adviceBean = new ControllerAdviceBean(new MyControllerAdvice());
Object adviceBean = createControllerAdviceBean(MyControllerAdvice.class);
RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(Collections.singletonList(adviceBean));
String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType,
@@ -120,7 +122,7 @@ class RequestResponseBodyAdviceChainTests {
@Test
void controllerAdviceNotApplicable() {
Object adviceBean = new ControllerAdviceBean(new TargetedControllerAdvice());
Object adviceBean = createControllerAdviceBean(TargetedControllerAdvice.class);
RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(Collections.singletonList(adviceBean));
String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType,
@@ -129,6 +131,13 @@ class RequestResponseBodyAdviceChainTests {
assertThat(actual).isEqualTo(this.body);
}
private ControllerAdviceBean createControllerAdviceBean(Class<?> beanType) {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton(beanType.getSimpleName(), beanType);
ControllerAdvice controllerAdvice = AnnotatedElementUtils.findMergedAnnotation(beanType, ControllerAdvice.class);
return new ControllerAdviceBean(beanType.getSimpleName(), applicationContext, controllerAdvice);
}
@ControllerAdvice
private static class MyControllerAdvice implements ResponseBodyAdvice<String> {