【SpringBoot】springboot的启动初步理解

springboot的启动初步理解

我们会发现开发一个Spring Boot,都会有一个注解@SpringBootApplication和一个类定义SpringApplication.run,点击源码可以查看到如下代码:

复制代码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
....
}

其实这里最重要的是以下三个注解:

@SpringBootConfiguration 该注解点开看里面是引入了@Configuration

@EnableAutoConfiguration 开启springboot的注解功能

@ComponentScan 扫描路径设置

其实我们的程序启动类,可以使用以下三个注解依然可以启动 @Configuration @EnableAutoConfiguration @ComponentScan,但是我们通常都是使用@SpringBootApplication

在启动类里面标注了@Configuration,意味着它其实也是一个 ioc容器的配置类,任何一个标注了@Configuration的Java类定义都是一个JavaConfig配置类。

任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IOC容器,方法名将默认成该bean定义的id。

基于JavaConfig的配置形式是这样的:

@Configuration

public class TestConfiguration{

@Bean

public TestService testService(){

return new TestServiceImpl(tempService());

}

@Bean

public TempService tempService(){

return new TempServiceImpl();

}

}

@ComponentScan

@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中。

我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。

@ComponentScan:

ComponentScan 默认会扫描当前 package 下的的所有加

了@Component 、@Repository、@Service、@Controller的类到 IoC 容器中;

相关推荐
程序员清风4 分钟前
AI不是万能的,大家要专注实践!
java·后端·面试
青山木5 分钟前
Hot 100 --- 全排列
java·数据结构·算法·leetcode·深度优先
猫猫不是喵喵.13 分钟前
认证授权【Spring Security】
java·认证授权
小罗水13 分钟前
第1章 大模型、企业知识库与 RAG 平台概述
java·spring
刘沅18 分钟前
Redis的哨兵机制
后端·面试
不知疲倦的仄仄20 分钟前
MySQL/Read View快照/MVCC/串行化
java·数据库·mysql
AmazingEgg20 分钟前
从 LIKE 到 Elasticsearch:博客搜索引擎可插拔改造全记录
后端
未秃头的程序猿21 分钟前
MCP协议火了,但到底怎么用?我花了一个周末用Java接入了5个MCP Server
后端·ai编程·mcp
Cosolar22 分钟前
Claude Opus 5 系统提示词被完整泄露,共 135027 字符、约 3.4 万 token
人工智能·后端·架构
Alan_7523 分钟前
RESTful API 落地的三个核心:资源建模、语义约束与工程化
后端