404 not found — Spring boot

Kobe
Nov 14, 2022

--

The questions

Q1: @SpringBootApplication What package is it in?

Q2: What package is your controller in?

By default, Spring boot component scanning occurs in the package of your main application class, or sub-packages. com.example.Controller is not a sub-package of com.example.demo

You could specify the name of the package to scan for components like this:

@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.controller"})

So now you can define a @RestController in your class below 2 packages com.example.demo & com.example.controller

package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("api")
public class DemoController {

@GetMapping("/hello")
public String sayHello(@RequestParam(value = "myName", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}

Access your API : http://localhost:8080/api/hello

Hello World!

--

--

Kobe
Kobe

Written by Kobe

I’m working at KMS-Technology company. I love code (▀̿Ĺ̯▀̿ ̿) — Full Stack Software Engineer

No responses yet