I am trying a write RestControllerAdvice which is part of a common library that I want to be available on a present of a certain property. As per our common library, we define all bean via configuration but not with annotation so that we can import that configuration class on demand instead of creating those beans always. But I am finding it difficult to mention that bean is actually of type RestControllerAdvice type in a spring configuration class.
Below is my RestControllerAdvice. I remove the @RestControllerAdvice
from this ExceptionHandler otherwise this bean will be created anyways and in my configuration class I added @AliasFor(annotation = RestControllerAdvice.class)
but I am not sure if its a correct way and it didn't work either.
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionHandler {
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<Void> handleMyException(CustomException e) {
return new ResponseEntity(new UnauthorizedResponse().withMessage(e.getMessage()).withStatus(HttpStatus.UNAUTHORIZED.value()), null, HttpStatus.UNAUTHORIZED);
}
}
@Configuration
public class ServiceCommonConfiguration {
@Bean
@AliasFor(annotation = RestControllerAdvice.class)
@ConditionalOnProperty(name = PROPERTY, havingValue = "enable")
public ExceptionHandler serviceCommonExceptionHandler() {
return new ExceptionHandler();
}
}