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
CodePudding user response:
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.
CodePudding user response:
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);
}
}