Search code examples
javatomcatjerseyjax-rs

Simple JAX-RS with Tomcat - 404 Not Found (No web.xml)


SERVICE

    @Path("/rest")
    public class JustService {

        @GET
        @Produces("text/plain")
        @Path("sayhi")
        public String sayhi(){
            return "Hi";
        }
     }

Application Config

@ApplicationPath("/*")
public class ApplicationConfig extends Application {

}

Tomcat Runs on port 8080 and heres the Postman request I'm sending : localhost:8080/rest/sayhi
response

"status": 404,
    "error": "Not Found",
    "message": "No message available",

Here's the POM.XML :

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

FIX Anyone stuck on this problem here's the fix -> as @cassiomolin suggested In your ApplicationConfig change the extended class from Application to -> ResourceConfig, and then add :

@Component
public class JerseyConfig() extends ResourceConfig{
    // I also changed the name of class to JerseyConfig (this is optional of course )

     public JerseyConfig() {
         register(JustService.class);
     }
     //change JustService to your service class and add as many register's as service classes you have.
    // you can add @ApplicationPath annotation to this class if you need to

Solution

  • Remove the spring-boot-starter-web dependency and use only the spring-boot-starter-jersey dependency. Then annotate the JustService class with @Component:

    @Component
    @Path("/rest")
    public class JustService {
        ...
    }
    

    And finally add the following class to your application:

    @Component
    public class JerseyConfig extends ResourceConfig {
    
        public JerseyConfig() {
            register(JustService.class);
        }
    }
    

    For more details, refer to the Spring Boot documentation.