relentless-coder
relentless-coder

Reputation: 1536

Spring Boot controller returns 404 for all api endpoints

I am new to Spring's ecosystem. And I am stuck with this particular situation. My application server responds with 404 for all of my API endpoints.

This is my controller

package com.example.controllers;

import com.example.models.Movie;
import com.example.services.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
public class MovieController {

    @Autowired
    private MovieService movieService;

    @RequestMapping(value = "/movies", method = RequestMethod.GET)
    @ResponseBody
    public List<Movie> getAllMovies(){
        return movieService.getAllMovies();
    }

    @RequestMapping(value = "/movies", method = RequestMethod.POST)
    @ResponseBody
    public Movie addNewMovie(@RequestBody Movie movie){
        System.out.println("Hello World");
        return movieService.addMovie(movie);
    }

    @RequestMapping(value = "/movies/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Optional<Movie> getMovieById(@PathVariable String id){
        return movieService.getMovieById(id);
    }

    @RequestMapping(value = "/movies", method = RequestMethod.PUT)
    @ResponseBody
    public Movie updateMovie(@RequestBody Movie movie){
        return movieService.updateMovie(movie);
    }

    @RequestMapping(value = "/movies/{id}", method = RequestMethod.DELETE)
    public void removeMovieById(@PathVariable String id){
        movieService.deleteMovie(id);
    }
}

And this my main class

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan
@SpringBootApplication
public class LearnSpringApplication{
    public static void main(String[] args) {
        SpringApplication.run(LearnSpringApplication.class, args);
    }
}

I am running it on localhost and port is 8080. I did set up a small app prior to this one, and that worked as expected. However, I am guessing that it's because the controller is in a different package since in the previous app, the main class and the controller were in the same package.

Edit Here's my pom.xml file:

<?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.example</groupId>
    <artifactId>learn_spring</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>

    <name>learn_spring</name>
    <description>Project to learn Spring</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.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>10</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

EDIT My Spring-Boot startup logs are

2018-05-03 17:16:44.937  INFO 14017 --- [           main] com.example.LearnSpringApplication       : Starting LearnSpringApplication v0.0.1 on tfc with PID 14017 (/home/ayush/Workspace/learn_spring/target/learn_spring-0.0.1.jar started by ayush in /home/ayush/Workspace/learn_spring)
2018-05-03 17:16:44.940  INFO 14017 --- [           main] com.example.LearnSpringApplication       : No active profile set, falling back to default profiles: default
2018-05-03 17:16:45.045  INFO 14017 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aba2b86: startup date [Thu May 03 17:16:45 IST 2018]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (jar:file:/home/ayush/Workspace/learn_spring/target/learn_spring-0.0.1.jar!/BOOT-INF/lib/spring-core-5.0.5.RELEASE.jar!/) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2018-05-03 17:16:46.113  INFO 14017 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-05-03 17:16:46.138  INFO 14017 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-05-03 17:16:46.139  INFO 14017 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-05-03 17:16:46.151  INFO 14017 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]
2018-05-03 17:16:46.218  INFO 14017 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-05-03 17:16:46.218  INFO 14017 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1186 ms
2018-05-03 17:16:46.336  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-05-03 17:16:46.339  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-03 17:16:46.340  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-03 17:16:46.340  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-03 17:16:46.340  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-03 17:16:46.455  INFO 14017 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:46.720  INFO 14017 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aba2b86: startup date [Thu May 03 17:16:45 IST 2018]; root of context hierarchy
2018-05-03 17:16:46.786  INFO 14017 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-03 17:16:46.787  INFO 14017 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-03 17:16:46.817  INFO 14017 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:46.817  INFO 14017 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:47.060  INFO 14017 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-03 17:16:47.151  INFO 14017 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:12}] to localhost:27017
2018-05-03 17:16:47.155  INFO 14017 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=null, roundTripTimeNanos=2192957}
2018-05-03 17:16:47.323  INFO 14017 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-03 17:16:47.392  INFO 14017 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-03 17:16:47.395  INFO 14017 --- [           main] com.example.LearnSpringApplication       : Started LearnSpringApplication in 2.89 seconds (JVM running for 3.296)

Upvotes: 12

Views: 24298

Answers (4)

Behzod Faiziev
Behzod Faiziev

Reputation: 445

While configuring application.yml I have added:

server:
    port: 8080
    servlet:
        context-path: /demoApp

where

  servlet:
  context-path: /demoApp 

was causing 404 error. By updating server as:

server:
    port: 8080

I could get my app working

Note: you may may be using application.properties, which is the same as

server.port=8080
server.servlet.context-path=/demoApp

So just remove

server.servlet.context-path=/demoApp

Upvotes: 0

Aatif
Aatif

Reputation: 21

I had the same problem today and tried the simple solution provided above by @Daniel Moshi. It worked fine. Thanks.

Other option is using like below: @SpringBootApplication(scanBasePackages = "com.example")

...with this the Controller can stay in any sub-package of com.example and works good even without explicit usage of @ComponentScan.

Upvotes: 0

Daniel Moshi
Daniel Moshi

Reputation: 181

Sometimes is because of your package structure. Always make sure your controllers are in same package or sub-package level as the @SpringBootApplication class.

For example:

If application class is at com.a.b then controllers should be at com.a.b or com.a.b.c or com.a.b.c.d etc. You don't always have to add @ComponentScan to get them registered.

Upvotes: 18

TwiN
TwiN

Reputation: 3834

You're using IntelliJ IDEA community version, which does not support the Spring Framework:

see https://www.jetbrains.com/idea/features/editions_comparison_matrix.html for reference

Update

Since you're using the command line, then the above does not apply. I'll leave it here as a reference, though.


In the comments, you have specified that when running mvn clean package followed by java -jar target/whatever-your-project-name-is.jar, you get the following error:

Field movieService in com.example.controllers.MovieController required a bean of type 'com.example.services.MovieService' that could not be found.

Please make sure that:

  • you have a class MovieService in the package services
  • that class is annotated with the @Service annotation

Update 2

Since the above did not work, try replacing

@ComponentScan 

by

@ComponentScan({"com.example.services", "com.example.controllers"})

in your LearnSpringApplication class.

Include all other packages that have classes annotated with @Component, @Service, @Controller, @RestController, or @Repository.

Note that this is a workaround. Normally, having @ComponentScan alone should be sufficient -- or as @DarrenForsythe mentionned in the comment, even just @SpringBootApplication should be sufficient for your case.

Upvotes: 4

Related Questions