You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中@SpringBootApplication(scanBasePackages)的底层工作机制

关于@SpringBootApplication(scanBasePackages = {"com.controller"})的底层运行原理

你的代码结构

DemoApplication 类(com.demo包)

package com.demo;

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

@SpringBootApplication(scanBasePackages = {"com.controller"})
public class DemoApplication {

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

AuthController 类(com.controller包)

package com.controller;

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

@RestController
public class AuthController {

    @GetMapping(value = "/welcome")
    public String welocome() {
        return "welcome bro..";
    }
}

底层执行的核心操作

当你在DemoApplication上标注@SpringBootApplication(scanBasePackages = {"com.controller"})时,Spring Boot底层会按以下流程运行:

  • 注解解析:首先解析@SpringBootApplication这个复合注解,它打包了@ComponentScan、@SpringBootConfiguration、@EnableAutoConfiguration三个核心注解。你指定的scanBasePackages参数会直接传给@ComponentScan,明确告诉Spring要扫描的根包是com.controller。

  • 组件扫描启动:Spring上下文初始化时,启动组件扫描器,遍历com.controller包及其所有子包:

    • 逐个检查类上是否带有@Component或它的衍生注解(比如@RestController、@Service、@Repository);
    • 对符合条件的类,生成对应的Bean定义(BeanDefinition),并注册到Spring的Bean工厂里。
  • 识别并注册Controller Bean:扫描到AuthController时,因为@RestController是@Controller+@ResponseBody的组合,而@Controller本身继承自@Component,所以这个类会被标记为Spring需要管理的Bean,它的定义会被存入ApplicationContext的BeanDefinitionMap中。

  • 自动配置Web环境:@SpringBootApplication包含的@EnableAutoConfiguration会触发自动配置机制,自动加载Web相关的配置类(比如DispatcherServletAutoConfiguration、WebMvcAutoConfiguration),帮你搭建好Spring MVC的基础框架——比如注册DispatcherServlet、配置请求路由规则等。

  • Bean实例化与初始化:在上下文刷新阶段,Spring会根据之前注册的Bean定义,实例化AuthController,完成依赖注入、初始化方法调用等流程,最终把这个实例放进Spring容器中托管。

  • 注册请求映射:AuthController里的@GetMapping("/welcome")会被Spring MVC的RequestMappingHandlerMapping识别,把这个方法注册成/welcome路径的请求处理器,当外部请求这个路径时,就能直接路由到该方法处理。

内容的提问来源于stack exchange,提问作者HERMES

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:24:54