Using @ControllerAdvice as a dependency for another project

Viewed 2099

I make a common project for listening Exceptions and use @ControllerAdvice with @ExceptionHandler

@ControllerAdvice(annotations = RestController.class)
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

     @ExceptionHandler({Exception.class})
     @ResponseStatus(value = HttpStatus.NOT_FOUND)
     @ResponseBody
     public ResponseEntity<ErrorResponse> notFound(Exception ex) {
         return new ResponseEntity<>(
            new ErrorResponse(ex.getMessage(), 404, "My Custom Message"), HttpStatus.NOT_FOUND);
     }
}

without any @SpringBootApplication and main method to adding as dependency to my another project. my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.test</groupId>
<artifactId>spring-commons-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring-commons-rest</name>
<description>for Listening Exceptions</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>

after adding its dependency and @ComponentScan to another project, but its not working as Exception handling for response custom Error. I appreciated any help.

2 Answers

I found that was not about using @ComponentScan and with using @Import it will work so fine. but if anyone has any better solution or some guiding line I will appreciate that.

I've solved it by adding

@Order(Ordered.HIGHEST_PRECEDENCE)

to the ControllerAdvice class that you are importing.

In my case there was another ControllerAdvice class in the downstream project that was taking priority over the one I was importing.

Related