SpringBoot面试宝典:20道高频考点及深度解析

🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
在这里插入图片描述

SpringBoot面试宝典:20道高频考点及深度解析

一、Spring Boot 基础概念

1.1 Spring Boot 是什么?

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的配置方式,从而使开发人员不再需要定义样板化的配置。通过 Spring Boot,开发者可以快速搭建一个独立的、生产级别的 Spring 应用。

示例代码:创建一个简单的 Spring Boot 应用启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MySpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApp.class, args);
    }
}

1.2 Spring Boot 有哪些优点?

  • 快速开发:Spring Boot 提供了各种 Starter 依赖,通过简单的添加依赖就可以集成各种功能,如 Web 开发、数据库访问等。
  • 自动配置:根据项目中引入的依赖,Spring Boot 会自动进行合理的配置,减少了大量的手动配置工作。
  • 独立运行:Spring Boot 应用可以打包成一个可执行的 JAR 或 WAR 文件,独立运行,无需外部的 Servlet 容器。
  • 生产就绪:Spring Boot 提供了丰富的监控和管理功能,如 Actuator,可以方便地对应用进行监控和管理。

二、Spring Boot 配置文件

2.1 Spring Boot 支持哪些配置文件格式?

Spring Boot 支持多种配置文件格式,主要包括 application.propertiesapplication.yml

2.1.1 application.properties

这是最传统的配置文件格式,使用键值对的形式进行配置。
示例:

server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
2.1.2 application.yml

YAML 格式的配置文件,使用缩进和冒号来表示层级关系,更加简洁易读。
示例:

server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: 123456

2.2 如何在 Spring Boot 中使用多环境配置?

Spring Boot 支持多环境配置,可以通过 application-{profile}.propertiesapplication-{profile}.yml 文件来实现。

步骤如下:

  1. 创建不同环境的配置文件,如 application-dev.propertiesapplication-prod.properties
  2. application.properties 中指定激活的环境:
spring.profiles.active=dev
  1. 当应用启动时,会加载 application-dev.properties 中的配置。

三、Spring Boot Starter

3.1 什么是 Spring Boot Starter?

Spring Boot Starter 是一组方便的依赖描述符,它可以简化 Maven 或 Gradle 配置。当你添加一个 Starter 依赖时,Spring Boot 会自动添加与之相关的所有依赖。

例如,添加 spring-boot-starter-web 依赖,就可以快速搭建一个 Web 应用:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3.2 如何自定义 Spring Boot Starter?

自定义 Spring Boot Starter 可以按照以下步骤进行:

  1. 创建一个 Maven 项目,添加必要的依赖。
  2. 创建自动配置类,使用 @Configuration@ConditionalOnClass 等注解进行条件配置。
  3. 创建 META-INF/spring.factories 文件,指定自动配置类的全限定名。

示例代码:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAutoConfiguration {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

META-INF/spring.factories 文件内容:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.MyAutoConfiguration

四、Spring Boot 注解

4.1 @SpringBootApplication 注解的作用是什么?

@SpringBootApplication 是一个组合注解,它包含了 @Configuration@EnableAutoConfiguration@ComponentScan 注解。

  • @Configuration:表示该类是一个配置类,相当于 Spring 的 XML 配置文件。
  • @EnableAutoConfiguration:启用 Spring Boot 的自动配置功能。
  • @ComponentScan:自动扫描包下的组件,如 @Controller@Service 等。

4.2 @Value 注解和 @ConfigurationProperties 注解的区别是什么?

  • @Value 注解:用于从配置文件中获取单个属性的值,通常用于注入简单类型的属性。
    示例:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    @Value("${my.property}")
    private String myProperty;

    // getter 和 setter 方法
}
  • @ConfigurationProperties 注解:用于将配置文件中的属性批量绑定到一个 Java 对象上,通常用于注入复杂类型的属性。
    示例:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "my")
public class MyConfig {
    private String property;

    // getter 和 setter 方法
}

五、Spring Boot 集成

5.1 如何在 Spring Boot 中集成 MyBatis?

步骤如下:

  1. 添加 mybatis-spring-boot-starter 依赖:
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.3.1</version>
</dependency>
  1. 配置数据源:在 application.propertiesapplication.yml 中配置数据库连接信息。
  2. 创建实体类和 Mapper 接口。
    示例:
// 实体类
public class User {
    private Long id;
    private String name;

    // getter 和 setter 方法
}

// Mapper 接口
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface UserMapper {
    List<User> findAll();
}
  1. application.yml 中配置 MyBatis 的映射文件路径:
mybatis:
  mapper-locations: classpath:mapper/*.xml

5.2 如何在 Spring Boot 中集成 Redis?

步骤如下:

  1. 添加 spring-boot-starter-data-redis 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置 Redis 连接信息:在 application.propertiesapplication.yml 中配置 Redis 的主机、端口等信息。
spring.redis.host=localhost
spring.redis.port=6379
  1. 使用 RedisTemplateStringRedisTemplate 进行 Redis 操作。
    示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setValue(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
}

六、Spring Boot Actuator

6.1 什么是 Spring Boot Actuator?

Spring Boot Actuator 是 Spring Boot 提供的一个用于监控和管理应用的模块,它提供了一系列的端点(Endpoint),可以通过 HTTP 或 JMX 访问这些端点来获取应用的运行状态、配置信息等。

6.2 如何启用和使用 Spring Boot Actuator?

步骤如下:

  1. 添加 spring-boot-starter-actuator 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. application.propertiesapplication.yml 中配置需要暴露的端点:
management.endpoints.web.exposure.include=*
  1. 访问端点,如 /actuator/health 可以查看应用的健康状态。

七、Spring Boot 安全

7.1 如何在 Spring Boot 中集成 Spring Security?

步骤如下:

  1. 添加 spring-boot-starter-security 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. 创建安全配置类,继承 WebSecurityConfigurerAdapter 类,并重写相关方法。
    示例:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/public/**").permitAll()
               .anyRequest().authenticated()
               .and()
           .formLogin()
               .and()
           .httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

7.2 如何实现基于角色的访问控制?

在 Spring Security 中,可以通过 @PreAuthorize 注解或配置文件来实现基于角色的访问控制。

示例:使用 @PreAuthorize 注解

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminPage() {
        return "This is an admin page.";
    }
}

八、Spring Boot 性能优化

8.1 如何优化 Spring Boot 应用的启动时间?

  • 减少依赖:移除不必要的依赖,避免加载过多的类。
  • 使用缓存:使用 Spring 的缓存机制,减少重复计算。
  • 异步初始化:使用 @Async 注解将一些耗时的初始化操作异步执行。

8.2 如何优化 Spring Boot 应用的内存使用?

  • 合理配置堆内存:根据应用的实际情况,合理配置 JVM 的堆内存大小。
  • 使用对象池:对于一些频繁创建和销毁的对象,使用对象池来复用对象。
  • 及时释放资源:确保在使用完资源后及时释放,如数据库连接、文件句柄等。

九、Spring Boot 部署

9.1 如何将 Spring Boot 应用打包成可执行的 JAR 文件?

使用 Maven 或 Gradle 进行打包,在 pom.xml 中添加以下插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

然后在命令行中执行 mvn clean package 命令,即可在 target 目录下生成可执行的 JAR 文件。

9.2 如何将 Spring Boot 应用部署到 Docker 容器中?

步骤如下:

  1. 创建 Dockerfile 文件:
FROM openjdk:11
COPY target/myapp.jar /app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
  1. 构建 Docker 镜像:在 Dockerfile 所在目录下执行 docker build -t myapp . 命令。
  2. 运行 Docker 容器:执行 docker run -p 8080:8080 myapp 命令。

十、Spring Boot 常见问题及解决方法

10.1 Spring Boot 应用启动失败,如何排查问题?

  • 查看日志:查看应用的启动日志,通常日志中会给出详细的错误信息。
  • 检查配置文件:确保配置文件中的配置信息正确,如数据库连接信息、端口号等。
  • 检查依赖:检查项目中的依赖是否存在冲突或版本不兼容的问题。

10.2 如何解决 Spring Boot 应用中的跨域问题?

可以通过配置 CorsFilter 来解决跨域问题。
示例代码:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanxbl957

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值