0

I am facing an issue with Spring mvc annotation @Controlleradvice. I have 2 controller classes: UserGapsController and RegistrationBaseController Both classes use

  1. @Controller
  2. @Controlleradvice
  3. @Autowired session object
  4. @Scope(WebApplicationContext.SCOPE_SESSION)

@Controlleradvice annotation has to be used when @Modelattribute is used at method level. So i am having a method annotated with @Modelattribute in both classes. Now problem is when i am using @Controlleradvice in just UserGapsController.java , application runs fine , when i use @Controlleradvice in RegistrationBaseController.java also , it breaks down at runtime with following error:

error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.requestmappinghandler: invocation of init method failed:nested exceotion is org.springframework.beans.factory.BeanCreationException :Error creating bean with name 'userGapsController' : Scope 'session' is not active for current thread

What is the reason for this error , can not we have 2 @Controlleradvice annotated classes ? When I comment @Controlleradvice in RegistrationBaseController.java , it executes fine then.

  • 1
    If you want two classes two have @controlleradvice then simply add @Order(Ordered.HIGHEST_PRECEDENCE) annotation. It will work – Arun Prasat Nov 29 '20 at 13:05
  • @ArunPrasat Sorry if i sound stupid , but i am new to spring. so we cant have 2 classes having controlleradvice annotation ? if yes , the what is the logic behind ? My understanding was controlleradvice is used where we use ModelAttribute at method level. Is my understanding wrong ? – Shweta Priyadarshani Nov 29 '20 at 18:18
  • 1
    > @Controlleradvice annotation has to be used when @Modelattribute is used at method level. That isn't true, an `@ModelAttribute` works in a regular controller perfectly fine. Only if you want an `@ModeLAttribute` method that applies to all controller then you need an `@ControllerAdvice` – M. Deinum Nov 30 '20 at 19:12

1 Answers1

1

You trying to have multiple @ControllerAdvice classes that handle different exceptions.

You can use Order over controllerAdvice like this

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RegistrationExceptionHandler {

    //...

}

and

@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE) // or any int value
public class UserGapsExceptionHandler {

    //...

}
MyTwoCents
  • 7,284
  • 3
  • 24
  • 52
  • Sorry if i sound stupid , but i am new to spring. so we cant have 2 classes having controlleradvice annotation ? if yes , the what is the logic behind ? My understanding was controlleradvice is used where we use ModelAttribute at method level. Is my understanding wrong ? – Shweta Priyadarshani Nov 29 '20 at 18:17