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

相关推荐
⑩-1 小时前
SpringCloud-Sleuth链路追踪实战
后端·spring·spring cloud
SUPER52661 小时前
本地开发环境_spring-ai项目启动异常
java·人工智能·spring
冷崖1 小时前
原子锁操作
c++·后端
moxiaoran57531 小时前
Spring AOP开发的使用场景
java·后端·spring
一线大码5 小时前
Gradle 基础篇之基础知识的介绍和使用
后端·gradle
Java猿_6 小时前
Spring Boot 集成 Sa-Token 实现登录认证与 RBAC 权限控制(实战)
android·spring boot·后端
小王师傅666 小时前
【轻松入门SpringBoot】actuator健康检查(上)
java·spring boot·后端
醒过来摸鱼6 小时前
Java classloader
java·开发语言·python
专注于大数据技术栈6 小时前
java学习--StringBuilder
java·学习
loosenivy6 小时前
企业银行账户归属地查询接口如何用Java调用
java·企业银行账户归属地·企业账户查询接口·企业银行账户查询