转载-SpringBoot自动配置实现原理

本文深入解析SpringBoot的启动流程,从run方法到应用上下文的创建,揭示自动配置类如何工作,以及约定大于配置的设计理念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.youkuaiyun.com/qq_38455201/article/details/81990564

我们在使用Spring Boot构建Java Web项目的时候,实现起来非常的简单,那么SpringBoot是如何做到看似简单,却能够实现我们之前使用SSM或者SSH结合复杂配置实现的功能的呢?

我们在看Spring Boot的介绍的时候,常看到下面一段话:Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。Spring Boot采用约定大约配置的方式,大量的减少了配置文件的使用。那么,Spring Boot是如何做到约定大于配置的呢?

首先我们看一下Spring Boot的主程序功能,也就是Spring Boot官方文档里面写的,你可以直接run


 
 
  1. @SpringBootApplication
  2. public class Application {
  3. public static void main(String[] args) {
  4. SpringApplication.run(Application.class, args);
  5. }
  6. }

一个非常简单的run方法的执行,加上@SpringBootApplication的注解,我们看一下run方法的源代码:


 
 
  1. public class SpringApplication{
  2. ......
  3. public ConfigurableApplicationContext run(String... args) {
  4. //监控任务执行时间
  5. StopWatch stopWatch = new StopWatch();
  6. stopWatch.start();
  7. //创建应用上下文
  8. ConfigurableApplicationContext context = null;
  9. //用来记录关于启动的错误报告
  10. Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
  11. configureHeadlessProperty();
  12. //可以监听springboot应用启动过程中的一些生命周期事件
  13. SpringApplicationRunListeners listeners = getRunListeners(args);
  14. listeners.starting();
  15. try {
  16. //程序运行参数
  17. ApplicationArguments applicationArguments = new DefaultApplicationArguments(
  18. args);
  19. //加载相关的配置文件
  20. ConfigurableEnvironment environment = prepareEnvironment(listeners,
  21. applicationArguments);
  22. configureIgnoreBeanInfo(environment);
  23. //打印Banner,也就是springboot启动后最开始打印的图像
  24. Banner printedBanner = printBanner(environment);
  25. //真正的创建应用上下文
  26. context = createApplicationContext();
  27. exceptionReporters = getSpringFactoriesInstances(
  28. SpringBootExceptionReporter.class,
  29. new Class[] { ConfigurableApplicationContext.class }, context);
  30. prepareContext(context, environment, listeners, applicationArguments,
  31. printedBanner);
  32. refreshContext(context);
  33. afterRefresh(context, applicationArguments);
  34. stopWatch.stop();
  35. if ( this.logStartupInfo) {
  36. new StartupInfoLogger( this.mainApplicationClass)
  37. .logStarted(getApplicationLog(), stopWatch);
  38. }
  39. listeners.started(context);
  40. callRunners(context, applicationArguments);
  41. }
  42. catch (Throwable ex) {
  43. handleRunFailure(context, ex, exceptionReporters, listeners);
  44. throw new IllegalStateException(ex);
  45. }
  46. try {
  47. listeners.running(context);
  48. }
  49. catch (Throwable ex) {
  50. handleRunFailure(context, ex, exceptionReporters, null);
  51. throw new IllegalStateException(ex);
  52. }
  53. return context;
  54. }
  55. ......
  56. }

在上面这段run方法的源代码当中,有一个context = createApplicationContext();方法


 
 
  1. protected ConfigurableApplicationContext createApplicationContext() {
  2. Class<?> contextClass = this.applicationContextClass;
  3. if (contextClass == null) {
  4. try {
  5. switch ( this.webApplicationType) {
  6. case SERVLET:
  7. //假如是servlet应用,默认加载DEFAULT_WEB_CONTEXT_CLASS
  8. contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
  9. break;
  10. case REACTIVE:
  11. contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
  12. break;
  13. default:
  14. contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
  15. }
  16. }
  17. catch (ClassNotFoundException ex) {
  18. throw new IllegalStateException(
  19. "Unable create a default ApplicationContext, "
  20. + "please specify an ApplicationContextClass",
  21. ex);
  22. }
  23. }
  24. return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
  25. }

也就是说,通过一个简单的run方法,将引发的是一系列复杂的内部调用和加载过程,从而初始化一个应用所需的配置、环境、资源以及各种自定义的类。在这个阶段,会导入一些列自动配置的类,实现强大的自动配置的功能。那么自动配置类是从哪里来的呢?这就需要@SpringBootApplicaton起到作用了。


 
 
  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @SpringBootConfiguration
  6. @EnableAutoConfiguration
  7. @ComponentScan(excludeFilters = {
  8. @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  9. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  10. public @interface SpringBootApplication {
  11. ......
  12. }

其中,@ComponentScan将扫描和加载一些自定义的类,@EnableAutoConfiguration将导入一些自动配置的类。这些自动配置的类很多,并且他们都处于org.springframework.boot.autoconfigure这个包下面。这些配置类都会被导入并处于备用状态。假如你在maven文件当中引入了相关的包的时候,相关功能将被启用。

那么,我们说的springboot约定大于配置是什么意思呢?自动配置在加载一个类的时候,会首先去读取项目当中的配置文件,假如没有,就会启用默认值,这就是springboot约定大于配置原理。以Thymeleaf为例:看下下面我们就知道,为什么我们使用Thymeleaf模板引擎,html文件默认放在resources下面的templates文件夹下面,因为这是Thymeleaf的默认配置。


 
 
  1. @ConfigurationProperties(prefix = "spring.thymeleaf")
  2. public class ThymeleafProperties {
  3. private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
  4. public static final String DEFAULT_PREFIX = "classpath:/templates/";
  5. public static final String DEFAULT_SUFFIX = ".html";
  6. private boolean checkTemplate = true;
  7. private boolean checkTemplateLocation = true;
  8. private String prefix = DEFAULT_PREFIX;
  9. private String suffix = DEFAULT_SUFFIX;
  10. private String mode = "HTML";
  11. private Charset encoding = DEFAULT_ENCODING;
  12. private boolean cache = true;
  13. ......
  14. }

并且这些约定的配置一般都以Properties为结尾,比如

org.springframework.boot.autoconfigure.jdbc.DataSourceProperties(数据库连接配置)

org.springframework.boot.autoconfigure.data.redis.RedisProperties(Redis连接配置)

org.springframework.boot.autoconfigure.amqp.RabbitProperties(RabbitMQ连接配置)

org.springframework.boot.autoconfigure.web.ResourceProperties(Web资源配置)

org.springframework.boot.autoconfigure.kafka.KafkaProperties(Kafka连接配置)

org.springframework.boot.autoconfigure.cache.CacheProperties(缓存配置)

那么,我们知道程序会自动装配加载很多类,但是我们假如不想程序去加载某些类(毕竟加载需要耗时),我们如何去自定义我们想加载的配置类呢?

我们只需要把@SpringBootApplication注解去掉,换成@Congfiguation注解,并通过@Import注解去指定需要加载的配置类就可以了(非常不建议这么做,因为我们可能不是特别了解所有自动加载的类的特性)。


 
 
  1. @Configuration
  2. @Import({
  3. DispatcherServletAutoConfiguration.class,
  4. HttpEncodingAutoConfiguration.class,
  5. ThymeleafAutoConfiguration.class,
  6. WebMvcAutoConfiguration.class,
  7. WebSocketServletAutoConfiguration.class,
  8. MultipartAutoConfiguration.class
  9. //继续加载你需要的配置
  10. })
  11. public class Application {
  12. public static void main(String[] args) {
  13. SpringApplication.run(Application.class, args);
  14. }
  15. }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值