Skip to content

Document ControllerAdviceBean as internal usage #32776

@sinanoezdemir

Description

@sinanoezdemir

Enhancement/ Misleading description in javadoc.

In the Javadoc of ControllerAdviceBean you can read

Encapsulates information about an @ControllerAdvice Spring-managed bean without necessarily requiring it to be instantiated.
The findAnnotatedBeans(ApplicationContext) method can be used to discover such beans. However, a ControllerAdviceBean may be created from any object, including ones without an @ControllerAdvice annotation.

ControllerAdviceBean

Reading this I assume, that it should be possible to create ControllerAdviceBeans and register them programmatically (without using the @ControllerAdvice annotation).

As far as I understood the ExceptionHandlerExceptionResolver is the class keeping the ControllerAdviceBeans to apply matching ExceptionHandlers when an exception occurs.

However, when initialising the exceptionHandlerAdviceCache it uses ControllerAdviceBean.findAnnotatedBeans which scans the application context for beans annotated with @ControllerAdvice.

The exceptionHandlerAdviceCache is otherwise not modifiable. So there is actually no other way to add ControllerAdviseBeans besides using the annotation.

I think that's why the Javadoc is misleading.

However, it would be great to have the ability to define ControllerAdviseBeans without using the @ControllerAdvice annotation.

  • Context: I am developing in a micro service environment and we have multiple micro services using the same ControllerAdvise which we extracted into a Library. I do not want libraries to contain spring component annotations. I rather would like to instantiate a bean in the configurations of each micro service. With the current implementation it's not possible to "just" remove the annotation and instantiate that bean in a configuration.

I assumed something similar to this should work.

@Configuration
public class SomeConfiguration {

  @Bean
  public ControllerAdviceBean myControllerAdvice() {
    return new ControllerAdviceBean(new MyControllerAdvice());
  }

}

//Example
public  class MyControllerAdvise {

    @ExceptionHandler({Exception.class})
    public ResponseEntity<Object> handleRemainingExceptions(Exception exception, WebRequest request) {
      // does something
      return ResponseEntity.internalServerError().body("Something went wrong");
    }
    
 }

Please excuse me if I misunderstood a concept here. Just trying to suggest an improvement.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: documentationA documentation task

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions