SpringBoot组件扫描

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot组件扫描

望天边星宿   2022-06-18 我要评论

参考视频:https://www.bilibili.com/video/BV1Bq4y1Q7GZ?p=6

通过视频的学习和自身的理解整理出的笔记。

一、前期准备

1.1 创建工程

创建springboot项目,springboot版本为2.5.0,引入spring-boot-starter-web依赖,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

1.2 创建Controller

创建一个简单的Controller用于测试

@RestController
public class HelloController {
    public void helloController() {
        System.out.println("创建了");
    }
    @RequestMapping("hello")
    public String hello() {
        return "hello";
    }
}

二、探究过程

2.1 探究目标

在项目中我们创建了Controller,这个Controller是如何被spring自动加载的呢?为什么Controller必须放在启动类的同级目录下呢?

如果我们想要加载不在启动类同级目录下的bean对象,需要在启动类中使用@ComponentScan注解。

目标:SpringBoot项目中我们没有设置组件扫描的包,为什么它会默认扫描启动类目录下所有的包。

2.2 探究过程

2.2.1 回顾容器bean的创建与刷新

在SpringApplication的run()方法中,创建了spring容器context,并通过refreshContext(context)更新容器加载我们自定义的bean对象。

我们发现在执行完refreshContext(context)代码后,自定义的bean对象(HelloController)就已经被创建了,说明refreshContext(context)过程中创建了自定义bean对象。

下面我们看看究竟是refreshContext(context)中哪些方法创建了自定义bean对象。

2.2.2 SpringApplication

我接着看refreshContext(context)方法

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们