Loading...

Spring Boot @Controlleradvice example : 2018

345 5________

@Controlleradvice is an annotation that allows you to write a code globally using which you can utilize that for different controllers.

when I say controllers what do you mean by that? It is a common terminology used in Java. According to MVC, Controller methods are the ones
which has the logic or you can also tell they are the brains for the tasks to be performed.

So controlleradvice is accessed by different controllers written throughout the package.

By default, @ControllerAdvice will be applicable to all the classes that use the @Controller annotation. (these classes are the ones using @RestController annotation).
To be specific, there are a few properties provided that allow this.

Now, what we explained is a more generic. If we want to reduce the applicable classes down by package, we need to add the name of the package to the annotation.
It is as simple as that. When a package is chosen, it will be enabled for classes inside that package as well as sub-packages.


@ControllerAdvice("my.package")
@ControllerAdvice(value = "my.package")
@ControllerAdvice(basePackages = "my.package")

Now, using basePackageClasses property also you can mention a package. This will enable @ControllerAdvice to all controllers inside the package that the class resides.
@ControllerAdvice(basePackageClasses = Example.class)

Now, using assignableTypes you can specify like this.
@ControllerAdvice(assignableTypes = Thisisacontrollr.class)

why you should use @ControllerAdvice?

Using @ControllerAdvice along with @ExceptionHandler prevents duplication by providing global error handling so you don’t need to remember to implement them yourself or extend another class every time.
Hence it is recommended to use @controlleradvice to keep the logic centralized , and as we apply this globally, you can be tension free about whether more general exceptions are being handled or not

Thank you for watching this video

コメント