Spring Boot作为一个强大的框架,其简化的配置和快速启动特性深受开发者喜爱。在本篇博客中,我们将深入探讨Spring Boot的启动过程,并分享一些在日常开发中可以参考的实例,包括工厂类的使用、设计模式的应用以及代码优化的技巧。
一、Spring Boot启动过程详解
Spring Boot的启动过程主要分为以下几个步骤:
- SpringApplication初始化
- 准备环境(Prepare Environment)
- 创建应用上下文(Create Application Context)
- 刷新应用上下文(Refresh Application Context)
- 完成运行(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
类中,通过模板方法定义了刷新上下文的步骤。
四、代码优化技巧
-
使用@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,并在实际开发中有所参考。