🌟博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
SpringBoot面试宝典:20道高频考点与源码解析
一、SpringBoot基础概念
1.1 SpringBoot是什么
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的配置方式,使得开发人员不再需要定义样板化的配置。通过 Spring Boot,可以快速构建独立的、生产级别的基于 Spring 框架的应用程序。
1.2 SpringBoot的优点
- 快速搭建:通过 Spring Initializr 可以快速生成项目骨架,集成了常见的依赖,节省开发时间。
- 自动配置:Spring Boot 自动根据项目中添加的依赖进行配置,减少了大量的 XML 配置文件。
- 内嵌服务器:支持内嵌 Tomcat、Jetty 等服务器,无需额外部署服务器。
- 监控与管理:提供了 Actuator 模块,方便对应用进行监控和管理。
1.3 SpringBoot的核心注解
- @SpringBootApplication:这是一个组合注解,包含了 @SpringBootConfiguration、@EnableAutoConfiguration 和 @ComponentScan 三个注解。它是 Spring Boot 应用的核心注解,用于标记一个主类,启动 Spring Boot 应用。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
- @EnableAutoConfiguration:启用 Spring Boot 的自动配置机制,根据类路径中的依赖自动配置 Spring 应用。
- @ComponentScan:自动扫描指定包及其子包下的组件,如 @Component、@Service、@Repository 等注解标注的类。
二、SpringBoot配置相关
2.1 配置文件类型
- application.properties:传统的键值对配置文件,语法简单,如:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
- application.yml:采用 YAML 语法,结构清晰,可读性强,如:
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
2.2 多环境配置
Spring Boot 支持多环境配置,通过 spring.profiles.active 属性指定当前使用的环境。例如,创建 application-dev.properties 和 application-prod.properties 分别用于开发和生产环境。
# application.properties
spring.profiles.active=dev
# application-dev.properties
server.port=8080
# application-prod.properties
server.port=80
2.3 自定义配置属性
可以通过 @ConfigurationProperties 注解将配置文件中的属性映射到 Java 类中。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfigProperties {
private String name;
private int age;
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
myconfig:
name: John
age: 30
三、SpringBoot依赖管理
3.1 Starter依赖
Spring Boot Starter 是一组方便的依赖描述符,它可以简化依赖管理。例如,spring-boot-starter-web 包含了开发 Web 应用所需的所有依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.2 版本管理
Spring Boot 通过 spring-boot-dependencies 来管理依赖的版本。在 Maven 项目中,可以通过继承 spring-boot-starter-parent 来自动引入版本管理。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
四、SpringBoot Web开发
4.1 构建 RESTful API
使用 Spring Boot 可以轻松构建 RESTful API。以下是一个简单的示例:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
4.2 拦截器
可以通过实现 HandlerInterceptor 接口来创建拦截器,用于在请求处理前后进行一些操作。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre-handle request");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
System.out.println("Post-handle request");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Request completed");
}
}
然后在配置类中注册拦截器:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
4.3 异常处理
可以通过 @ControllerAdvice 和 @ExceptionHandler 注解来统一处理异常。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
五、SpringBoot数据库操作
5.1 Spring Data JPA
Spring Data JPA 是 Spring 提供的一个简化 JPA 开发的框架。以下是一个简单的示例:
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.entity.User;
public interface UserRepository extends JpaRepository<User, Long> {
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5.2 MyBatis集成
可以通过 mybatis-spring-boot-starter 来集成 MyBatis。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
定义 Mapper 接口:
import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);
}
六、SpringBoot源码解析
6.1 SpringApplication启动流程
SpringApplication 的启动流程主要包括以下几个步骤:
- 创建 SpringApplication 实例。
- 调用
run方法。 - 初始化监听器和应用上下文。
- 刷新应用上下文。
以下是部分源码解析:
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
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();
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
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, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
6.2 自动配置原理
Spring Boot 的自动配置是基于 @EnableAutoConfiguration 注解实现的。该注解会触发 AutoConfigurationImportSelector 类的 selectImports 方法,该方法会从 META-INF/spring.factories 文件中读取所有的自动配置类,并根据条件进行筛选和加载。
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
七、20道高频面试题及答案
7.1 基础概念类
- 什么是 Spring Boot?
答:Spring Boot 是用于简化 Spring 应用开发的框架,它提供了自动配置、内嵌服务器等功能,减少了样板化配置,提高了开发效率。 - Spring Boot 有哪些优点?
答:快速搭建、自动配置、内嵌服务器、监控与管理方便等。 - Spring Boot 的核心注解有哪些?
答:@SpringBootApplication、@EnableAutoConfiguration、@ComponentScan 等。
7.2 配置相关类
- Spring Boot 支持哪些配置文件类型?
答:application.properties 和 application.yml。 - 如何实现 Spring Boot 的多环境配置?
答:通过spring.profiles.active属性指定当前使用的环境,创建不同环境的配置文件,如application-dev.properties和application-prod.properties。 - 如何自定义 Spring Boot 的配置属性?
答:使用@ConfigurationProperties注解将配置文件中的属性映射到 Java 类中。
7.3 依赖管理类
- 什么是 Spring Boot Starter?
答:Spring Boot Starter 是一组方便的依赖描述符,它可以简化依赖管理,包含了开发特定类型应用所需的所有依赖。 - 如何管理 Spring Boot 依赖的版本?
答:可以通过继承spring-boot-starter-parent来自动引入版本管理。
7.4 Web开发类
- 如何在 Spring Boot 中构建 RESTful API?
答:使用@RestController和@RequestMapping等注解来创建控制器和处理请求。 - 什么是 Spring Boot 拦截器?如何使用?
答:拦截器用于在请求处理前后进行一些操作。可以通过实现HandlerInterceptor接口创建拦截器,并在配置类中注册。 - 如何在 Spring Boot 中统一处理异常?
答:使用@ControllerAdvice和@ExceptionHandler注解来统一处理异常。
7.5 数据库操作类
- 什么是 Spring Data JPA?
答:Spring Data JPA 是 Spring 提供的一个简化 JPA 开发的框架,通过定义接口即可实现基本的数据库操作。 - 如何在 Spring Boot 中集成 MyBatis?
答:通过mybatis-spring-boot-starter来集成 MyBatis,定义 Mapper 接口和 SQL 语句。
7.6 源码解析类
- 简述 SpringApplication 的启动流程。
答:创建 SpringApplication 实例,调用run方法,初始化监听器和应用上下文,刷新应用上下文。 - 解释 Spring Boot 自动配置的原理。
答:基于@EnableAutoConfiguration注解触发AutoConfigurationImportSelector类的selectImports方法,从META-INF/spring.factories文件中读取所有的自动配置类,并根据条件进行筛选和加载。
7.7 其他类
- Spring Boot 如何实现热部署?
答:可以使用 Spring Boot DevTools 实现热部署,它会监控类路径下的文件变化,当文件发生变化时自动重启应用。 - 如何在 Spring Boot 中使用 Actuator 进行监控和管理?
答:添加spring-boot-starter-actuator依赖,通过访问特定的端点(如/actuator/health)来获取应用的监控信息。 - Spring Boot 与 Spring Cloud 有什么关系?
答:Spring Boot 是构建独立应用的框架,Spring Cloud 是基于 Spring Boot 构建的分布式系统开发工具集,Spring Cloud 依赖于 Spring Boot 来简化开发。 - 如何在 Spring Boot 中使用缓存?
答:可以使用 Spring Cache 抽象,添加相应的缓存依赖(如 Redis),并使用@Cacheable、@CachePut等注解来实现缓存功能。 - 什么是 Spring Boot 的条件注解?
答:条件注解(如@ConditionalOnClass、@ConditionalOnMissingBean等)用于根据特定条件来决定是否加载某个 Bean 或配置类。


349

被折叠的 条评论
为什么被折叠?



