Spring - Using an exception handler from an external jar for 2 other projects

2.3k views Asked by At

I have 2 projects that have the same exceptions and use the same exception handler. So all of the exceptions and the exception handler were moved to an external module.

The exceptions are imported just fine, but the exception handler does not seem to be invoked. As far as I understand, the handler should be invoked from the external jar if I have the @ComponentScan annotation.

Here's how my exception handler looks like:

@ComponentScan(basePackages = {"com.*first-project*.controller",
        "com.*second-project*.controller"})
@ControllerAdvice(basePackages = {"com.*first-project*.controller",
        "com.*second-project*.controller"})
public class GlobalExceptionHandler {

...

}

The exception handler worked fine when it was part of each project individually. Then it only had that project's path in the @ControllerAdvice annotation and had no @ComponentScan.

The external jar with the exception handler is currently imported with:

compile files('libs/*jar-name*.jar')
3

There are 3 answers

0
Rivfader On BEST ANSWER

Adding @Import(GlobalExceptionHandler.class) in the projects fixed the issue and the handler is being invoked properly now.

4
Aman On

You should properly scan the components, both from the main project and from the extended jar. This scanning should be done on the main project(project-1 & project-2).

So, in project-1 & project-2, you have to scan the packages found in jar-name. You can create a separate configuration file or in your GlobalExceptionHandler.

@ControllerAdvice(basePackages = {"jar.package"})
public class GlobalExceptionHandler {...}
0
Ajay Gupta On

I was also facing the same issue what I did is:

Step 1: In GlobalExceptionHandler.java declare controller as base > packages using @ComponenetScan and @ControllerAdvice. Like as below

@ComponentScan(basePackages = "com.xxx.controller") @ControllerAdvice(basePackages = "com.xxx.controller") class GlobalExceptionHandler extends ResponseEntityExceptionHandler{}

Step 2: use @Import annotation and import GlobalExceptionHandler class > >in SpringbootMain Application class. Like as below @SpringBootApplication @Import(CustomExceptionHandler.class) public class SpringBootDemoApplication { }

Step 3: Include GlobalExceptionHandler maven dependency in other service projects wherever you want to use it.