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?
Rest Controller works just for Application class
415 Views Asked by AleXeNoN At
2
The issue is that your package structure prevents
BookController
from being component scanned.When you have your
@SpringBootApplication
defined in packagecom.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 inbook
, 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 movebook.BookController
to be atcom.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:Or, define a different
@ComponentScan
. Note that the configuration class annotated with@ComponentScan
must still be component scanned itself.