您的位置:首页 > 健康 > 养生 > 深入Spring Boot启动过程:揭秘设计模式与代码优化秘籍

深入Spring Boot启动过程:揭秘设计模式与代码优化秘籍

2024/10/6 18:27:35 来源:https://blog.csdn.net/zcs_978176963/article/details/140190654  浏览:    关键词:深入Spring Boot启动过程:揭秘设计模式与代码优化秘籍

Spring Boot作为一个强大的框架,其简化的配置和快速启动特性深受开发者喜爱。在本篇博客中,我们将深入探讨Spring Boot的启动过程,并分享一些在日常开发中可以参考的实例,包括工厂类的使用、设计模式的应用以及代码优化的技巧。

一、Spring Boot启动过程详解

Spring Boot的启动过程主要分为以下几个步骤:

  1. SpringApplication初始化
  2. 准备环境(Prepare Environment)
  3. 创建应用上下文(Create Application Context)
  4. 刷新应用上下文(Refresh Application Context)
  5. 完成运行(Run Application)
1. SpringApplication初始化

SpringApplication类是Spring Boot应用启动的核心。其主要职责包括:

  • 初始化应用程序上下文
  • 设置应用启动参数
  • 加载和应用Spring Boot的自动配置

在创建SpringApplication实例时,主要执行了以下操作:

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {this.resourceLoader = resourceLoader;Assert.notNull(primarySources, "PrimarySources must not be null");this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));this.webApplicationType = WebApplicationType.deduceFromClasspath();this.setInitializers((Collection) this.getSpringFactoriesInstances(ApplicationContextInitializer.class));this.setListeners((Collection) this.getSpringFactoriesInstances(ApplicationListener.class));this.mainApplicationClass = this.deduceMainApplicationClass();
}
2. 准备环境

在SpringApplication的run方法中,准备环境是一个重要的步骤。这个步骤主要是配置和加载环境变量和属性源,如application.properties或application.yml文件。

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,ApplicationArguments applicationArguments) {// Create and configure the environmentConfigurableEnvironment environment = getOrCreateEnvironment();configureEnvironment(environment, applicationArguments.getSourceArgs());listeners.environmentPrepared(environment);return environment;
}
3. 创建应用上下文

Spring Boot支持多种类型的应用上下文(如AnnotationConfigApplicationContext、AnnotationConfigEmbeddedWebApplicationContext等)。在创建上下文时,会根据应用类型(Web或非Web)选择相应的上下文类型。

private ConfigurableApplicationContext createApplicationContext() {Class<?> contextClass = this.applicationContextClass;if (contextClass == null) {try {switch (this.webApplicationType) {case SERVLET:contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);break;case REACTIVE:contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);break;default:contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);}} catch (ClassNotFoundException ex) {throw new IllegalStateException("Unable create a default ApplicationContext, " +"please specify an ApplicationContextClass", ex);}}return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
4. 刷新应用上下文

在Spring中,刷新上下文是一个重要的步骤,它会完成Bean的创建、加载和初始化。

public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {prepareRefresh();ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();prepareBeanFactory(beanFactory);postProcessBeanFactory(beanFactory);invokeBeanFactoryPostProcessors(beanFactory);registerBeanPostProcessors(beanFactory);initMessageSource();initApplicationEventMulticaster();onRefresh();registerListeners();finishBeanFactoryInitialization(beanFactory);finishRefresh();}
}
5. 完成运行

最后,Spring Boot完成所有准备工作并启动应用。

public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;configureHeadlessProperty();SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting();try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);configureIgnoreBeanInfo(environment);Banner printedBanner = printBanner(environment);context = createApplicationContext();prepareContext(context, environment, listeners, applicationArguments, printedBanner);refreshContext(context);afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);}listeners.started(context);callRunners(context, applicationArguments);} catch (Throwable ex) {handleRunFailure(context, ex, listeners);throw new IllegalStateException(ex);}return context;
}
二、开发中的工厂类应用

工厂模式是一种创建对象的设计模式。在Spring Boot中,工厂类的应用非常普遍。例如,Spring中的FactoryBean接口允许我们自定义Bean的创建逻辑。

public class MyBeanFactory implements FactoryBean<MyBean> {@Overridepublic MyBean getObject() throws Exception {return new MyBean();}@Overridepublic Class<?> getObjectType() {return MyBean.class;}@Overridepublic boolean isSingleton() {return true;}
}
三、设计模式的应用

在Spring Boot中,除了工厂模式,其他常见的设计模式也被广泛应用。例如:

  • 单例模式:Spring默认的Bean作用域就是单例的。
  • 代理模式:AOP(面向切面编程)就是代理模式的经典应用。
  • 模板方法模式:在AbstractApplicationContext类中,通过模板方法定义了刷新上下文的步骤。
四、代码优化技巧
  1. 使用@Value和@ConfigurationProperties管理配置: 使用@Value注解或者@ConfigurationProperties类来管理配置,可以使代码更简洁、可维护。

    @Value("${my.property}")
    private String myProperty;
    

    或者

    @ConfigurationProperties(prefix = "my")
    public class MyProperties {private String property;// getter and setter
    }
    
  2. 合理使用缓存: 使用Spring Cache抽象对常用数据进行缓存,提高性能。

    @Cacheable("items")
    public Item getItemById(Long id) {return itemRepository.findById(id).orElse(null);
    }
    
  3. 避免循环依赖: Spring的自动注入机制虽然方便,但容易引发循环依赖问题。可以通过构造函数注入和@Lazy注解来避免。

    @Autowired
    public MyService(@Lazy AnotherService anotherService) {this.anotherService = anotherService;
    }
    
  4. 异步处理: 使用@Async注解实现异步方法,提高应用响应速度。

    @Async
    public void executeAsyncTask() {// 异步任务
    }
    
总结

Spring Boot的启动过程包含了多个关键步骤,从初始化到上下文刷新,再到最后的运行完成,每一步都至关重要。在日常开发中,通过使用工厂类和设计模式,我们可以写出更加灵活和可维护的代码。同时,合理的代码优化技巧不仅能提升性能,还能使代码更加简洁易读。希望这篇文章能帮助你更好地理解Spring Boot,并在实际开发中有所参考。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com