简体   繁体   中英

How can I use a rest controller from a different package in Spring?

What's going on

I am using Java, Springboot I am trying to create a simple API.

I have a package called Example . I have two sub-packages called config and rest .

In config is the class Application , which is my spring app. In rest is the class TheController which is the rest controller

Currently when i run the app, Application and try and go to one of the get mappings i get a white label error page.

However if i move theController to the config package i do not get this error and it's plain sailing.

What I have tried

I have tried using an import statement. com.Example.rest.* and com.Example.rest.TheController with no results.

Any help would be appreciated :)

Add a @ComponentScan on your application class.

package com.example.config;

@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class SpringBootComponentScanApp {

}

I personally think it's a good idea to put your configuration in a sub-package "com.example.config" and not in the parent package "com.example", but you need to override Spring Boot's default component scan for that case.

See also https://www.baeldung.com/spring-component-scanning

Spring Boot will only scan for components (controllers, services, repositories, ...) starting from the package of the application class (annotated with @SpringBootApplication ) and below.

So best to use com.example.Application , then you can use com.example.rest.TheController and things should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM