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

简介: 深入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 environment
    ConfigurableEnvironment 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> {
 
    @Override
    public MyBean getObject() throws Exception {
        return new MyBean();
    }
 
    @Override
    public Class<?> getObjectType() {
        return MyBean.class;
    }
 
    @Override
    public boolean isSingleton() {
        return true;
    }
}
三、设计模式的应用

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

  • 单例模式:Spring默认的Bean作用域就是单例的。
  • 代理模式:AOP(面向切面编程)就是代理模式的经典应用。

模板方法模式:在AbstractApplicationContext类中,通过模板方法定义了刷新上下文的步骤。

四、代码优化技巧

使用@Value和@ConfigurationProperties管理配置: 使用@Value注解或者@ConfigurationProperties类来管理配置,可以使代码更简洁、可维护。

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

或者

@ConfigurationProperties(prefix = "my")
public class MyProperties {
    private String property;
    // getter and setter
}

合理使用缓存: 使用Spring Cache抽象对常用数据进行缓存,提高性能。

@Cacheable("items")
public Item getItemById(Long id) {
    return itemRepository.findById(id).orElse(null);
}

避免循环依赖: Spring的自动注入机制虽然方便,但容易引发循环依赖问题。可以通过构造函数注入和@Lazy注解来避免。

@Autowired
public MyService(@Lazy AnotherService anotherService) {
    this.anotherService = anotherService;
}

异步处理: 使用@Async注解实现异步方法,提高应用响应速度。

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

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

相关文章
|
5月前
|
设计模式 SQL Java
Spring中的设计模式
Spring中的设计模式
|
1月前
|
设计模式 Java 关系型数据库
【Java笔记+踩坑汇总】Java基础+JavaWeb+SSM+SpringBoot+SpringCloud+瑞吉外卖/谷粒商城/学成在线+设计模式+面试题汇总+性能调优/架构设计+源码解析
本文是“Java学习路线”专栏的导航文章,目标是为Java初学者和初中高级工程师提供一套完整的Java学习路线。
307 37
|
12天前
|
设计模式 缓存 Java
面试题:谈谈Spring用到了哪些设计模式?
面试题:谈谈Spring用到了哪些设计模式?
|
1月前
|
设计模式 Java Spring
spring源码设计模式分析-代理设计模式(二)
spring源码设计模式分析-代理设计模式(二)
|
2月前
|
设计模式 SQL Java
一探到底!Spring团队使用的那些设计模式,快来看看你用过哪几个
该文章主要介绍了Spring框架中使用的设计模式,并列举了一些常见的设计模式及其在Spring框架中的应用。
一探到底!Spring团队使用的那些设计模式,快来看看你用过哪几个
|
4月前
|
设计模式 Java 程序员
Spring用到了哪些设计模式?
Spring用到了哪些设计模式?
36 1
|
4月前
|
监控 Java Spring
深入理解Spring Boot的启动过程
深入理解Spring Boot的启动过程
|
5月前
|
XML Java 开发者
springboot 启动原理、启动过程、启动机制的介绍
【5月更文挑战第13天】Spring Boot 是一种基于 Java 的框架,用于创建独立的、生产级别的 Spring 应用程序。它的主要目标是简化 Spring 应用的初始搭建和开发过程,同时提供一系列大型项目常见的非功能性特征(如嵌入式服务器、安全性、度量、健康检查和外部化配置)。
343 3
|
5月前
|
设计模式 安全 Java
【初学者慎入】Spring源码中的16种设计模式实现
以上是威哥给大家整理了16种常见的设计模式在 Spring 源码中的运用,学习 Spring 源码成为了 Java 程序员的标配,你还知道Spring 中哪些源码中运用了设计模式,欢迎留言与威哥交流。
252 3