跳到主要内容 Spring Boot 核心架构与自动配置原理深度解析 | 极客日志
Java java
Spring Boot 核心架构与自动配置原理深度解析 深入解析 Spring Boot 的核心定位、自动配置原理及内嵌容器机制。涵盖@SpringBootApplication 注解拆解、条件注解实现逻辑、Tomcat 启动流程、多环境配置管理、Actuator 监控以及 Spring MVC 整合实战。通过源码分析展示自动配置加载过程,提供自定义 Starter、异步处理、打包部署等高级特性方案,并总结常见问题与性能优化要点,帮助开发者掌握 Spring Boot 核心技术与最佳实践。
RedisGeek 发布于 2026/3/21 更新于 2026/4/18 3 浏览一、Spring Boot 核心定位
Spring Boot 是基于 Spring 框架的快速开发脚手架 ,核心目标是简化 Spring 应用的初始化搭建和开发过程 ,解决了传统 Spring 应用「配置繁琐、依赖管理复杂、部署麻烦」的痛点。
核心理念:约定优于配置(Convention Over Configuration) ,通过默认配置减少开发者的配置工作;
核心优势:
自动配置 :根据引入的依赖自动配置 Spring 组件(如引入 spring-boot-starter-web 自动配置 Spring MVC);
起步依赖 :将常用依赖打包为 starter,一键引入即可使用(如 spring-boot-starter-web 包含 Spring MVC、Tomcat、Jackson 等);
嵌入式容器 :内置 Tomcat/Jetty/Undertow,无需手动部署 WAR 包,可直接运行 JAR 包;
简化监控 :通过 spring-boot-starter-actuator 快速实现应用监控;
无代码生成/无 XML 配置 :纯 Java 配置,开箱即用;
应用场景:所有 Spring 生态的应用开发(微服务、单体应用),是 Spring Cloud 微服务架构的基础。
二、Spring Boot 核心架构与自动配置原理
2.1 核心架构分层 Spring Boot 应用核心启动层(SpringApplication)
自动配置层(AutoConfiguration)
起步依赖层(Starter)
嵌入式容器层(Tomcat/Jetty)
Spring MVC 自动配置(WebMvcAutoConfiguration)
数据源自动配置(DataSourceAutoConfiguration)
事务自动配置(TransactionAutoConfiguration)
spring-boot-starter-web
spring-boot-starter-data-jpa
spring-boot-starter-security
TomcatAutoConfiguration
2.2 自动配置核心原理 自动配置是 Spring Boot 最核心的特性,也是其与传统 Spring 应用的核心区别,底层基于「条件注解 + 类路径扫描 + 动态 Bean 注册 」实现。
2.2.1 自动配置核心注解 注解 作用 示例 @SpringBootApplication核心注解,整合 3 个关键注解:@SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan 标注在启动类上 @EnableAutoConfiguration开启自动配置,触发 Spring Boot 扫描并加载自动配置类 核心底层注解 @AutoConfigurationSpring Boot 2.7+ 替代 @Configuration 的自动配置注解,控制配置加载顺序 @AutoConfiguration(after = WebMvcAutoConfiguration.class)@Conditional条件注解父类,满足指定条件才加载 Bean - @ConditionalOnClass类路径存在指定类时生效 @ConditionalOnClass({DispatcherServlet.class})@ConditionalOnMissingClass类路径不存在指定类时生效 - @ConditionalOnBean容器中存在指定 Bean 时生效 - @ConditionalOnMissingBean容器中不存在指定 Bean 时生效(允许自定义覆盖默认配置) @ConditionalOnMissingBean(HandlerMapping.class)@ConditionalOnProperty配置文件中存在指定属性时生效 @ConditionalOnProperty(prefix = "spring.mvc", name = "enabled", havingValue = "true")
2.2.2 自动配置核心流程
步骤 1:启动类触发自动配置
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main (String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)
})
public @interface SpringBootApplication {
Class<?>[] exclude() default {};
String[] excludeName() default {};
String[] scanBasePackages() default {};
}
步骤 2:@EnableAutoConfiguration 核心逻辑
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration" ;
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
protected AutoConfigurationEntry getAutoConfigurationEntry (AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry (configurations, exclusions);
}
步骤 3:自动配置类的加载与生效
Spring Boot 启动时,会扫描 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件(Spring Boot 2.7+),该文件包含所有自动配置类的全限定名;
每个自动配置类(如 WebMvcAutoConfiguration)通过 @Conditional 系列注解判断是否生效,例如:
@AutoConfiguration(after = {DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class WebMvcAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver () {
InternalResourceViewResolver resolver = new InternalResourceViewResolver ();
resolver.setPrefix(this .mvcProperties.getView().getPrefix());
resolver.setSuffix(this .mvcProperties.getView().getSuffix());
return resolver;
}
@Bean
@ConditionalOnMissingBean
public RequestMappingHandlerMapping requestMappingHandlerMapping () {
RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
return mapping;
}
@Bean
@ConditionalOnMissingBean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter () {
return adapter;
}
}
2.3 Spring Boot 启动流程(核心步骤)
初始化 SpringApplication :解析启动类、设置应用类型(Servlet/Reactive)、加载初始化器和监听器;
加载环境配置 :读取 application.yml/application.properties、命令行参数、系统属性等;
创建 ApplicationContext :根据应用类型创建 AnnotationConfigServletWebServerApplicationContext(Servlet 应用);
刷新容器 :
执行 BeanFactoryPostProcessor;
注册 BeanPostProcessor;
初始化 MessageSource;
初始化事件多播器;
初始化嵌入式 Servlet 容器(Tomcat);
注册并初始化所有 Bean;
启动嵌入式容器 :启动 Tomcat/Jetty,绑定端口;
执行启动后处理器 :触发 ApplicationReadyEvent 事件,应用启动完成。
三、Spring Boot 核心功能解析
3.1 内嵌 Tomcat 运行服务的实现原理 Spring Boot 实现内嵌 Tomcat 运行服务的核心逻辑是:通过自动配置创建 Tomcat 容器实例 → 将 Spring MVC 核心 Servlet(DispatcherServlet)注册到 Tomcat → 启动 Tomcat 并绑定端口监听请求 ,整个过程无需手动部署 WAR 包,完全由 Spring Boot 自动完成。
步骤 1:引入内嵌 Tomcat 依赖(基础前提) Spring Boot 的 spring-boot-starter-web 起步依赖会自动引入内嵌 Tomcat 的核心依赖,无需手动添加 Tomcat 相关 jar 包。
关键依赖(Maven)
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-tomcat</artifactId >
</dependency >
<dependency >
<groupId > org.apache.tomcat.embed</groupId >
<artifactId > tomcat-embed-core</artifactId >
</dependency >
<dependency >
<groupId > org.apache.tomcat.embed</groupId >
<artifactId > tomcat-embed-websocket</artifactId >
</dependency >
步骤 2:自动配置 Tomcat 容器工厂(核心触发) Spring Boot 通过 TomcatServletWebServerFactoryAutoConfiguration 自动配置类,创建 Tomcat 容器的工厂类 TomcatServletWebServerFactory,这是创建 Tomcat 实例的核心入口。
核心源码:TomcatServletWebServerFactoryAutoConfiguration
@AutoConfiguration
@ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class})
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
public class TomcatServletWebServerFactoryAutoConfiguration {
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory (
ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,
ObjectProvider<TomcatContextCustomizer> contextCustomizers,
ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory ();
factory.getTomcatConnectorCustomizers().addAll(connectorCustomizers.orderedStream().toList());
factory.getTomcatContextCustomizers().addAll(contextCustomizers.orderedStream().toList());
factory.getTomcatProtocolHandlerCustomizers().addAll(protocolHandlerCustomizers.orderedStream().toList());
return factory;
}
}
@ConditionalOnClass:确保类路径存在 Tomcat 核心类时才生效;
TomcatServletWebServerFactory:Tomcat 容器的工厂类,负责创建 TomcatWebServer(封装 Tomcat 实例的类)。
步骤 3:ApplicationContext 刷新时创建 Tomcat 容器 Spring Boot 启动的核心阶段是 ApplicationContext 的 refresh() 方法,对于 Web 应用(ServletWebServerApplicationContext),会在刷新过程中调用 createWebServer() 方法创建 Tomcat 容器。
核心源码:ServletWebServerApplicationContext public class ServletWebServerApplicationContext extends GenericWebApplicationContext implements ConfigurableWebServerApplicationContext {
private volatile WebServer webServer;
@Override
protected void onRefresh () {
super .onRefresh();
try {
createWebServer();
} catch (Throwable ex) {
throw new ApplicationContextException ("Unable to start web server" , ex);
}
}
private void createWebServer () {
WebServer webServer = this .webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null ) {
ServletWebServerFactory factory = getWebServerFactory();
this .webServer = factory.getWebServer(getSelfInitializer());
getBeanFactory().registerSingleton("webServerGracefulShutdown" , new WebServerGracefulShutdownLifecycle (this .webServer));
getBeanFactory().registerSingleton("webServerStartStop" , new WebServerStartStopLifecycle (this , this .webServer));
} else if (servletContext != null ) {
try {
getSelfInitializer().onStartup(servletContext);
} catch (ServletException ex) {
throw new ApplicationContextException ("Cannot initialize servlet context" , ex);
}
}
initPropertySources();
}
}
onRefresh():ApplicationContext 刷新时触发,是创建 Web 容器的核心时机;
factory.getWebServer():调用 TomcatServletWebServerFactory 的方法创建 TomcatWebServer(Tomcat 容器实例)。
步骤 4:TomcatWebServer 初始化 Tomcat 实例 TomcatServletWebServerFactory 的 getWebServer() 方法会创建 Tomcat 实例,配置连接器(Connector)、引擎(Engine)、主机(Host)、上下文(Context)等核心组件。
核心源码:TomcatServletWebServerFactory public class TomcatServletWebServerFactory extends AbstractServletWebServerFactory {
@Override
public WebServer getWebServer (ServletContextInitializer initializers) {
org.apache.catalina.startup.Tomcat tomcat = new org .apache.catalina.startup.Tomcat();
File baseDir = (this .baseDirectory != null ) ? this .baseDirectory : createTempDir("tomcat" );
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector (this .protocol);
connector.setThrowOnFailure(true );
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false );
prepareContext(tomcat.getHost(), initializers);
return new TomcatWebServer (tomcat, getPort() >= 0 , getShutdown());
}
}
核心源码:TomcatWebServer(Tomcat 实例封装) public class TomcatWebServer implements WebServer {
private final org.apache.catalina.startup.Tomcat tomcat;
private final boolean autoStart;
public TomcatWebServer (org.apache.catalina.startup.Tomcat tomcat, boolean autoStart) {
this .tomcat = tomcat;
this .autoStart = autoStart;
initialize();
}
private void initialize () throws WebServerException {
synchronized (this .monitor) {
try {
addInstanceIdToEngineName();
this .tomcat.start();
startDaemonAwaitThread();
} catch (Exception ex) {
stopSilently();
destroySilently();
throw new WebServerException ("Unable to start embedded Tomcat" , ex);
}
}
}
@Override
public void start () throws WebServerException {
synchronized (this .monitor) {
if (this .started) {
return ;
}
this .tomcat.start();
this .started = true ;
}
}
}
TomcatWebServer 封装了原生 Tomcat 实例,负责 Tomcat 的启动、停止;
tomcat.start():调用原生 Tomcat 的启动方法,启动连接器监听端口。
步骤 5:注册 DispatcherServlet 到 Tomcat Spring MVC 的核心 Servlet(DispatcherServlet)会被注册到 Tomcat 的 ServletContext 中,绑定默认的 / 路径,接收所有请求。
核心源码:DispatcherServletAutoConfiguration @AutoConfiguration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass(DispatcherServlet.class)
@AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class)
public class DispatcherServletAutoConfiguration {
@Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet (DispatcherServletProperties properties) {
DispatcherServlet dispatcherServlet = new DispatcherServlet ();
dispatcherServlet.setDispatchOptionsRequest(properties.isDispatchOptionsRequest());
dispatcherServlet.setDispatchTraceRequest(properties.isDispatchTraceRequest());
return dispatcherServlet;
}
@Bean
public DispatcherServletRegistrationBean dispatcherServletRegistrationBean (
DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties) {
DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean (
dispatcherServlet, webMvcProperties.getServlet().getPath());
registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());
if (webMvcProperties.getServlet().getMultipart() != null ) {
registration.setMultipartConfig(getMultipartConfig(webMvcProperties));
}
return registration;
}
}
DispatcherServletRegistrationBean:负责将 DispatcherServlet 注册到 Tomcat 的 ServletContext;
默认映射路径为 /:所有请求都会被 DispatcherServlet 接收,然后转发到对应的 Controller。
步骤 6:Tomcat 启动完成,监听端口处理请求 Tomcat 启动后,连接器(Connector)会监听配置的端口(默认 8080),当客户端发送请求时:
Tomcat 的连接器接收请求;
请求被转发到 DispatcherServlet;
DispatcherServlet 按照 Spring MVC 的流程处理请求(匹配 Controller、执行业务逻辑、返回响应);
Tomcat 将响应返回给客户端。
Spring Boot 中内嵌 Tomcat 的启动是:Spring Boot 应用上下文(ApplicationContext)执行 refresh() 刷新操作时,在 onRefresh() 方法中触发 createWebServer(),最终在 TomcatWebServer 初始化阶段调用原生 Tomcat 的 start() 方法完成启动 。
3.2 配置管理
3.2.1 配置文件类型
核心文件 :application.properties / application.yml(优先级:yml > properties);
多环境配置 :
application-dev.yml(开发环境);
application-test.yml(测试环境);
application-prod.yml(生产环境)。
3.2.2 激活多环境
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
logging:
level:
root: DEBUG
---
spring:
config:
activate:
on-profile: prod
server:
port: 80
logging:
level:
root: INFO
3.2.3 配置绑定(@ConfigurationProperties)
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String version;
private Database database;
public static class Database {
private String url;
private String username;
private String password;
}
}
app:
name: spring-boot-demo
version: 1.0 .0
database:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
3.3 嵌入式容器
3.3.1 默认容器(Tomcat)配置 server:
port: 8080
servlet:
context-path: /demo
tomcat:
uri-encoding: UTF-8
max-threads: 200
min-spare-threads: 10
basedir: tomcat-temp
3.3.2 切换容器(如 Jetty)
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
<exclusions >
<exclusion >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-tomcat</artifactId >
</exclusion >
</exclusions >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-jetty</artifactId >
</dependency >
3.4 应用监控(Actuator)
3.4.1 核心依赖 <dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-actuator</artifactId >
</dependency >
3.4.2 核心配置 management:
endpoints:
web:
exposure:
include: health,info,metrics,beans,env
base-path: /actuator
endpoint:
health:
show-details: always
metrics:
enabled: true
tags:
application: spring-boot-demo
3.4.3 常用端点 端点 功能 /actuator/health应用健康状态 /actuator/info应用自定义信息 /actuator/metrics应用指标(JVM、CPU、内存) /actuator/beans容器中所有 Bean 信息 /actuator/env环境配置信息 /actuator/mappingsSpring MVC 请求映射信息
四、Spring Boot 与 Spring MVC 整合实战
4.1 基础整合
4.1.1 核心依赖
<parent >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-parent</artifactId >
<version > 3.2.0</version >
<relativePath />
</parent >
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-test</artifactId >
<scope > test</scope >
</dependency >
</dependencies >
4.1.2 启动类 @SpringBootApplication
public class SpringMvcBootApplication {
public static void main (String[] args) {
SpringApplication.run(SpringMvcBootApplication.class, args);
}
}
4.1.3 控制器(Spring MVC) @RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<User> getUserById (@PathVariable Long id) {
User user = new User ();
user.setId(id);
user.setName("Spring Boot + MVC" );
user.setAge(20 );
return ResponseEntity.ok(user);
}
@PostMapping
public ResponseEntity<User> createUser (@RequestBody User user) {
user.setId(100L );
return ResponseEntity.status(HttpStatus.CREATED).body(user);
}
}
public class User {
private Long id;
private String name;
private Integer age;
}
4.1.4 配置文件(application.yml) server:
port: 8080
servlet:
context-path: /demo
spring:
mvc:
servlet:
load-on-startup: 1
format:
date: yyyy-MM-dd HH:mm:ss
web:
resources:
static-locations: classpath:/static/,classpath:/public/
4.2 自定义 Spring MVC 配置
4.2.1 扩展 WebMvcConfigurer @Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public LoginInterceptor loginInterceptor () {
return new LoginInterceptor ();
}
@Override
public void addInterceptors (InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor()).addPathPatterns("/api/**" ).excludePathPatterns("/api/login" );
}
@Override
public void configureMessageConverters (List<HttpMessageConverter<?>> converters) {
converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter ();
FastJsonConfig fastJsonConfig = new FastJsonConfig ();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss" );
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
fastJsonConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastJsonConverter);
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver (ITemplateResolver templateResolver) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver ();
resolver.setTemplateResolver(templateResolver);
resolver.setCharacterEncoding("UTF-8" );
return resolver;
}
@Override
public void addCorsMappings (CorsRegistry registry) {
registry.addMapping("/api/**" ).allowedOriginPatterns("*" ).allowedMethods("GET" ,"POST" ,"PUT" ,"DELETE" ).allowedHeaders("*" ).allowCredentials(true ).maxAge(3600 );
}
}
4.2.2 完全自定义 Spring MVC 配置(慎用) 若需要完全替换 Spring Boot 的默认 MVC 配置,可添加 @EnableWebMvc 注解(会禁用自动配置):
@Configuration
@EnableWebMvc
public class FullWebMvcConfig implements WebMvcConfigurer {
}
4.3 全局异常处理(Spring Boot + MVC) @RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidException (MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldError().getDefaultMessage();
ErrorResponse error = new ErrorResponse (400 , "参数错误" , message);
return ResponseEntity.badRequest().body(error);
}
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ErrorResponse> handleBusinessException (BusinessException e) {
ErrorResponse error = new ErrorResponse (e.getCode(), "业务异常" , e.getMessage());
return ResponseEntity.status(e.getCode()).body(error);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException (Exception e) {
log.error("系统异常" , e);
ErrorResponse error = new ErrorResponse (500 , "服务器内部错误" , "系统繁忙,请稍后重试" );
return ResponseEntity.status(500 ).body(error);
}
@Data
@AllArgsConstructor
public static class ErrorResponse {
private int code;
private String type;
private String message;
}
}
五、Spring Boot 高级特性
5.1 外部化配置优先级 Spring Boot 加载配置的优先级(从高到低):
命令行参数(如 java -jar app.jar --server.port=8081);
系统环境变量;
应用外部的 application-{profile}.yml;
应用内部的 application-{profile}.yml;
应用外部的 application.yml;
应用内部的 application.yml;
@PropertySource 注解加载的配置;
默认配置(Spring Boot 自动配置)。
5.2 自定义启动 Banner
在 resources 目录下创建 banner.txt 文件;
写入自定义 Banner(可通过 Banner 生成工具 生成):
____ _ _ _ _ _
| _ \ | | | | | | | | ( _) | | _) | __ _| | _| | _| | ___ ___| | __ _ _ __ | _ < / _` | __| __| |/ _ \/ __| '_ \| | '_ \| |_) | (_| | |_| |_| | __/\__ \ | | | | |_) | |____/ \__,_|\__|\__|_|\___||___/_| |_|_| .__/ | | |_| :: Spring Boot :: (3.2.0)
5.3 异步处理
5.3.1 异步控制器 @RestController
@RequestMapping("/async")
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/callable")
public Callable<ResponseEntity<String>> asyncCallable () {
return () -> {
Thread.sleep(3000 );
return ResponseEntity.ok("异步响应(Callable)" );
};
}
@GetMapping("/future")
public CompletableFuture<ResponseEntity<String>> asyncFuture () {
return asyncService.doAsyncTask();
}
}
@Service
public class AsyncService {
@Async
public CompletableFuture<ResponseEntity<String>> doAsyncTask () {
try {
Thread.sleep(3000 );
return CompletableFuture.completedFuture(ResponseEntity.ok("异步响应(CompletableFuture)" ));
} catch (InterruptedException e) {
return CompletableFuture.failedFuture(e);
}
}
}
@SpringBootApplication
@EnableAsync
public class SpringBootDemoApplication {
@Bean
public Executor taskExecutor () {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor ();
executor.setCorePoolSize(5 );
executor.setMaxPoolSize(10 );
executor.setQueueCapacity(20 );
executor.setThreadNamePrefix("async-" );
executor.setRejectedExecutionHandler(new ThreadPoolExecutor .CallerRunsPolicy());
executor.initialize();
return executor;
}
}
5.4 打包与部署
5.4.1 打包为 JAR 包 mvn clean package -DskipTests
java -jar target/spring-boot-demo-1.0.0.jar
java -jar target/spring-boot-demo-1.0.0.jar --spring.config.location=file:/opt/config/application.yml
java -jar target/spring-boot-demo-1.0.0.jar --server.port=8081
5.4.2 打包为 WAR 包
<packaging > war</packaging >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
<exclusions >
<exclusion >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-tomcat</artifactId >
</exclusion >
</exclusions >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-tomcat</artifactId >
<scope > provided</scope >
</dependency >
@SpringBootApplication
public class SpringBootDemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure (SpringApplicationBuilder application) {
return application.sources(SpringBootDemoApplication.class);
}
public static void main (String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
mvn clean package -DskipTests
六、Spring Boot 常见问题
6.1 基础概念类
Spring Boot 的核心注解是什么?各部分作用?
@SpringBootApplication:核心注解,整合 @SpringBootConfiguration(配置类)、@EnableAutoConfiguration(自动配置)、@ComponentScan(组件扫描);
@EnableAutoConfiguration:开启自动配置,通过 AutoConfigurationImportSelector 加载自动配置类。
Spring Boot 自动配置原理?
核心:@EnableAutoConfiguration → AutoConfigurationImportSelector → 加载 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 中的自动配置类 → 通过 @Conditional 注解判断是否生效 → 注册默认 Bean(可通过 @ConditionalOnMissingBean 自定义覆盖)。
Spring Boot 与 Spring MVC 的关系?
Spring Boot 是开发脚手架,Spring MVC 是 Web 开发框架;
引入 spring-boot-starter-web 后,Spring Boot 通过 WebMvcAutoConfiguration 自动配置 Spring MVC 核心组件(DispatcherServlet、HandlerMapping、HandlerAdapter 等);
开发者可通过 WebMvcConfigurer 扩展 Spring MVC 配置,或通过 @EnableWebMvc 完全自定义。
6.2 实战问题类
如何自定义 Spring Boot 的自动配置?
步骤:
编写自动配置类(@Configuration + @Conditional 系列注解);
编写配置属性绑定类(@ConfigurationProperties);
在 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 中配置自动配置类全限定名;
打包为 starter,引入即可自动生效。
Spring Boot 如何实现多环境配置?
方式 1:通过 spring.profiles.active 激活指定环境(如 spring.profiles.active=prod);
方式 2:通过命令行参数激活(java -jar app.jar --spring.profiles.active=test);
方式 3:通过系统环境变量激活(SPRING_PROFILES_ACTIVE=dev)。
Spring Boot 启动失败,端口被占用如何解决?
方式 1:修改端口(server.port=8081);
方式 2:查找并杀死占用端口的进程(netstat -ano | findstr 8080 → taskkill /F /PID 进程 ID);
方式 3:配置端口随机(server.port=0)。
6.3 性能优化类
Spring Boot 应用性能优化要点?
容器优化:调整 Tomcat 线程池(server.tomcat.max-threads)、连接超时时间;
JVM 优化:设置 JVM 参数(-Xms512m -Xmx1024m);
依赖优化:移除无用 starter,减少依赖体积;
配置优化:关闭不必要的自动配置,启用缓存(如 Thymeleaf 缓存);
代码优化:使用异步处理(@Async)、减少拦截器耗时逻辑。
七、总结
核心关键点
核心定位 :Spring Boot 是 Spring 生态的快速开发脚手架,核心理念是「约定优于配置」,通过自动配置和起步依赖简化开发;
自动配置 :
核心触发点:@EnableAutoConfiguration → AutoConfigurationImportSelector → 加载自动配置类;
核心控制:@Conditional 系列注解(如 @ConditionalOnClass、@ConditionalOnMissingBean)控制配置是否生效;
与 Spring MVC 整合 :
引入 spring-boot-starter-web 自动配置 Spring MVC 核心组件;
通过 WebMvcConfigurer 扩展 MVC 配置(拦截器、跨域、消息转换器);
避免滥用 @EnableWebMvc(会禁用自动配置);
最佳实践 :
优先使用起步依赖,避免手动管理依赖版本;
多环境配置通过 spring.profiles.active 激活;
自定义配置优先使用 @ConfigurationProperties 绑定,而非 @Value;
部署优先选择 JAR 包(内置容器),简化部署流程;
应用监控引入 spring-boot-starter-actuator,实时监控应用状态。
微信扫一扫,关注极客日志 微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具 Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
JavaScript 压缩与混淆 Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online