【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 容器中;

相关推荐
2301_7703737332 分钟前
Java集合
java·开发语言
哈喽姥爷40 分钟前
Spring Boot---自动配置原理和自定义Starter
java·spring boot·后端·自定义starter·自动配置原理
小蒜学长1 小时前
基于springboot 校园餐厅预约点餐微信小程序的设计与实现(代码+数据库+LW)
数据库·spring boot·微信小程序
舒一笑2 小时前
为什么where=Version就是乐观锁了?
后端·mysql·程序员
GoGeekBaird2 小时前
关于垂类AI应用落地行业的方法论思考
后端·github·agent
小宁爱Python3 小时前
Django 基础入门:命令、结构与核心配置全解析
后端·python·django
老华带你飞3 小时前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·vue.js·spring boot·考研·小程序·毕设·考研论坛平台小程序
CHEN5_023 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_993 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
你的人类朋友3 小时前
认识一下Bcrypt哈希算法
后端·安全·程序员