0

I'm trying to do a getmapping method using rest-api which will return as a JSON on localhost: 8080. When I do this from the default Application class it works great but when I move this functionality to another class nothing happens. Could someone help me with this, please?

Application Class

BookController Class

Kai-Sheng Yang
  • 1,535
  • 4
  • 15
  • 21
AleXeNoN
  • 69
  • 6

2 Answers2

0

Reason 1: Default Spring's component scanning can't fount your @RestController component, so you can try to do @ComponentScan directly.

Reason 2: You need to specify an endpoint for your @GetMapping by using @RequestMapping/@GetMapping("url") or both of them.

zzzzz
  • 222
  • 2
  • 7
  • "You need to specify an endpoint for your @GetMapping" -- That is not needed. No value implies an empty path. That's why it is working in the first screenshot at the root path (`/``). – Knox May 22 '22 at 18:08
  • And I tried @RequestMapping for Book Class and didn't change anything – AleXeNoN May 22 '22 at 18:15
  • @ComponentScan also didn't work... – AleXeNoN May 22 '22 at 18:16
0

The issue is that your package structure prevents BookController from being component scanned.

When you have your @SpringBootApplication defined in package com.xenon.myspringbootapp, anything in that package and in nested packages is eligible for component scanning, which will register a bean out of @(Rest)Controller and other stereotypes.

Because BookController is defined in book, it is outside of the component scanned packages and will therefore not be component scanned by your @SpringBootApplication annotation.

See the reference docs for more best practices on package structure with Spring Boot applications.

To resolve this, there are two choices to get your class component scanned.

The first (and the way I would recommend) is just to restructure your packages so that the @SpringBootApplication class is at the "base" of your application packages. For example, you could move book.BookController to be at com.xenon.myspringbootapp.book.BookController.

The second is to change the component scanning configuration to include your book package. You can do this either on the @SpringBootApplication annotation itself:

@SpringBootApplication(scanBasePackages = {
        "com.xenon.myspringbootapp",
        "book"
})

Or, define a different @ComponentScan. Note that the configuration class annotated with @ComponentScan must still be component scanned itself.

@SpringBootApplication
public class MySpringBootAppApplication {

    @Configuration
    @ComponentScan("book")
    public static class MyBookComponentScanConfiguration {}

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootAppApplication.class);
    }
}
Knox
  • 1,150
  • 1
  • 14
  • 29