Home > Blockchain >  controller not registered in spring
controller not registered in spring

Time:04-07

I'm trying to add a controller to spring starter project, but the mapped path always return 404 error.

I first downloaded the maven project from https://start.spring.io/, then I created a controllers directory, and add a HomeController.java in src/main/java/com/example/controllers directory:

package com.example.controllers;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
    @GetMapping("/test")
    public String test() {
        return "123";
    }
}

And I launch the spring-boot application with mvn spring-boot:run, and test the /test with curl:

%> curl http://127.0.0.1:8080/test
{"timestamp":"2022-04-07T02:00:37.745 00:00","status":404,"error":"Not Found","path":"/test"}

What's wrong with the controller?

CodePudding user response:

I suggest you to refer some of this link https://spring.io/guides/gs/rest-service/

You need to let spring know which components need to be scanned and registered. So add @ComponentScan("com.example.controllers") to DemoApplication.

@ComponentScan("com.example.controllers")
@SpringBootApplication
public class DemoApplication {

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

}
  • Related