【多方法解决】SpringBoot启动正常,访问RestController报404

问题描述:SpringBoot启动正常,访问RestController报404

代码案例:

package controller;

import domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
 @GetMapping("/getOne")
    public String getOne(){
        System.out.println("你好");
        return "欢迎使用SpringBoot3";
    }

}

Springboot启动顺利:

顺利启动SpringBOotDemoApplication

访问失败:

根据案例IDEA或浏览器访问http://localhost:8080/getOne ,出现404错误
![访问失败](https://img-blog.csdnimg.cn/602ca7449cf14e27bc42e9624fd06b8a.png访问
目录结构
注意:文件的目录结构!!!

问题分析:默认情况下,SpringBoot只会扫描启动类当前包和以下的包

在这里插入图片描述

问题解决方法1:

在这个例子中,

主类:SpringBOotDemoApplication在包java.com.springbootdemo;

controller类放在包java.com中;

因为SpringBoot只会扫描启动类当前包和以下的包 ,所以上面这处情况是找不到controller的,所以出现404错误。

正确的做法是:
SpringBOotDemoApplication在包java.com.springbootdemo;
controller类放在com.springbootdemo.controller,这样相当于controller的在的包属于com.springbootdemo底下。这样默认情况下,SpringBoot就会扫描UserController类了。
成功访问截图

问题解决方法2:添加@SpringBootApplication(scanBasePackages=“controller”)

在主类的SpringBOotDemoApplication类中,添加注释,指定controller的位置,就可以指定加载,成功解决问题。
如下代码:

package com.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//@SpringBootApplication
@SpringBootApplication(scanBasePackages="controller")
public class SpringBOotDemoApplication {

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

}

目录结构如下

在这里插入图片描述

访问成功界面:

在这里插入图片描述

案例源码下载

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值