Spring REST Controller not mapped

时间:2016-10-20 18:42:11

标签: java spring rest controller

I'm trying to create à Rest controller that listen on "/login" I have defined the code bellow but when I open http://localhost:8080/login I get a 404 error... Please help :)

Here is my package structure:

com.my.package
   |_ Application.java
   |_ controller
          |_ LoginController

My Application:

@ComponentScan("com.my.package.controller")
@SpringBootApplication
public class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}

My Rest controller:

@RestController
public class LoginController {

    @RequestMapping("/login")
    public @ResponseBody String getLogin(){
        return "{}";
    }
}

3 个答案:

答案 0 :(得分:3)

控制器类应位于Application类的文件夹中或较低的文件夹中。

因此,如果应用程序类位于软件包com.company.app中,则控制器类应位于软件包com.company.appcom.company.app.*.中假设控制器类位于com.company.controller中,因为它不在应用程序类的同一包或子包中,所以不会被映射。

答案 1 :(得分:1)

You should use this annotations in your init class of your springBoot App

@Configuration
@EnableAutoConfiguration
@ComponentScan("com.my.package")
public class WebAppInitializer{

    public static void main(String[] args) throws Exception{
        SpringApplication.run(WebAppInitializer.class, args);
    }

}

答案 2 :(得分:0)

有时,当无法解释为什么映射不起作用时,只需更改服务器端口,使其不同于8080。

即。在application.properties或yml中,server.port = 8081