Spring Boot: Cannot access REST Controller on localhost (404)

前端 未结 18 1480
天命终不由人
天命终不由人 2020-11-27 12:05

I am trying to adapt the REST Controller example on the Spring Boot website. Unfortunately I\'ve got the following error when I am trying to access the localhost:8080/

相关标签:
18条回答
  • 2020-11-27 12:24

    Try adding the following to your InventoryApp class

    @SpringBootApplication
    @ComponentScan(basePackageClasses = ItemInventoryController.class)
    public class InventoryApp {
    ...
    

    spring-boot will scan for components in packages below com.nice.application, so if your controller is in com.nice.controller you need to scan for it explicitly.

    0 讨论(0)
  • 2020-11-27 12:24

    Sometimes spring boot behaves weird. I specified below in application class and it works:

    @ComponentScan("com.seic.deliveryautomation.controller")
    
    0 讨论(0)
  • 2020-11-27 12:24

    It also works if we use as follows:

    @SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })
    
    0 讨论(0)
  • 2020-11-27 12:25

    Another solution in case it helps: in my case, the problem was that I had a @RequestMapping("/xxx") at class level (in my controller), and in the exposed services I had @PostMapping (value = "/yyyy") and @GetMapping (value = "/zzz"); once I commented the @RequestMapping("/xxx") and managed all at method level, worked like a charm.

    0 讨论(0)
  • 2020-11-27 12:27

    Adding to MattR's answer:

    As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

    0 讨论(0)
  • 2020-11-27 12:27

    There are 2 method to overcome this

    1. Place the bootup application at start of the package structure and rest all controller inside it.

      Example :

      package com.spring.boot.app; - You bootup application(i.e. Main Method -SpringApplication.run(App.class, args);)

      You Rest Controller in with the same package structure Example : package com.spring.boot.app.rest;

    2. Explicitly define the Controller in the Bootup package.

    Method 1 is more cleaner.

    0 讨论(0)
提交回复
热议问题