I'm building a Spring-REST-API with CRUD-functionality to create, read, update and delete books with a MongoDB-database. My project has the following structure:
BackendBookLibraryApplication.java in main > java > com.lena.backendbooklibrary
BookController.java in main > java > com.lena.backendbooklibrary.controllers
package com.lena.backendbooklibrary;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BackendBookLibraryApplication {
public static void main(String[] args) {
SpringApplication.run(BackendBookLibraryApplication.class, args);
}
}
package com.lena.backendbooklibrary.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/books")
public class BookController {
@GetMapping
public String getAllBooks() {
return "All books";
}
}
When I am running my application the path http://localhost:8080/api/v1/books delivers a 404. I cannot find out why the SpringBootApplication can't find my REST-Controller, since they are in the same package (the Controller is in a sub package, but this should be no problem). In my console there aren't any errors.
I tried the following to delimit the problem:
- Annotated the BackendBookLibraryApplication with @RestController and implemented the GET-Method in there: this works
package com.lena.backendbooklibrary;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@RequestMapping("/api/v1/books")
public class BackendBookLibraryApplication {
public static void main(String[] args) {
SpringApplication.run(BackendBookLibraryApplication.class, args);
}
@GetMapping
public String getAllBooks() {
System.out.println("BackendBookLibraryApplication: getAllBooks()");
return "All books";
}
}
- Moved the BookController from the sub package into the exact same package com.lena.backendbooklibrary like the BackendBookLibraryApplication: this does not work
- Additionally annotated the BackendBookLibraryApplication with @ComponentScan(basePackageClasses = BookController.class), although I thought this should be summarised in the @SpringBootApplication-Annotation: this does not work
Does anyone have an idea what the problem is? It would be great if any Spring-expert could help me. Thanks in advance!