Spring Boot 面试热点(二)

在上一部分中,我们介绍了 Spring Boot 的优势、项目结构和自动配置原理。本部分将继续探讨 Spring Boot 的 Starter、配置文件和安全机制,这些都是面试中常见的问题。

1. Spring Boot Starter

常用 Starter

  • spring-boot-starter-web: 用于构建 web 应用,包含 Spring MVC 和内嵌的 Tomcat 服务器。
  • spring-boot-starter-data-jpa: 用于与数据库交互,包含 Hibernate 和 Spring Data JPA。
  • spring-boot-starter-security: 提供安全认证和授权功能。
  • spring-boot-starter-test: 提供常用的测试库,如 JUnit、Mockito 等。

自定义 Starter

  • 创建模块: 创建一个新的 Maven/Gradle 模块。
  • 添加依赖 : 在模块的 pom.xml 或 build.gradle 中添加依赖。
  • 自动配置 : 创建自动配置类,并在 META-INF/spring.factories 文件中注册。
  • 发布: 将模块发布到 Maven 中央仓库或内部仓库。

2. Spring Boot 配置文件

配置文件类型

  • application.properties: 默认的属性配置文件。
  • application.yml: 支持 YAML 格式的配置文件。

多环境配置

  • Profile : 通过 spring.profiles.active 属性指定激活的环境配置。
  • 多文件 : 使用 application-{profile}.properties 或 application-{profile}.yml 文件管理不同环境的配置。
properties 复制代码
# application.properties
spring.profiles.active=dev

# application-dev.properties
server.port=8081

# application-prod.properties
server.port=8080

外部配置

  • 命令行参数 : 通过命令行参数传递配置,如 --server.port=8080。
  • 环境变量 : 通过环境变量配置,如 export SERVER_PORT=8080。
  • 配置中心: 使用 Spring Cloud Config 等配置中心管理配置。

3. Spring Boot 安全

基本认证

  • 依赖 : 添加 spring-boot-starter-security 依赖。
  • 配置: 默认提供基于内存的用户名和密码认证。

自定义安全配置

  • 扩展 WebSecurityConfigurerAdapter : 自定义安全配置类,重写 configure 方法。

    java复制代码import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

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

JWT 认证

  • 依赖 : 添加 jjwt 依赖。
  • 生成和验证: 使用 JWT 生成和验证用户令牌,实现无状态认证。

结语

本文介绍了 Spring Boot 的 Starter、配置文件和安全机制,这些都是 Spring Boot 开发中非常重要的部分。通过熟练掌握这些内容,你可以在面试中展示出对 Spring Boot 深入理解和实际应用的能力。

相关推荐
小宋10217 分钟前
Agent 工具升级如何不破坏线上:Tool Schema 版本兼容与契约测试
java·人工智能·后端·spring
geovindu13 分钟前
rust: Flyweight Pattern
开发语言·后端·设计模式·rust·享元模式·结构型模式
我的xiaodoujiao14 分钟前
Django 基础知识详细图文教程 13-Django 模型定义与使用 3
数据库·后端·python·测试工具·oracle·django
EatFan16 分钟前
2026 后端 AI 集成三条落地路径:Spring AI 2.0、MCP 协议与旁路服务怎么选
java·人工智能·spring boot·spring·大模型·spring ai·mcp
SimonKing16 分钟前
QClaw关停之后:一个工具的退场,一段关系的告别
java·后端·程序员
不一样的少年_38 分钟前
别用前端思维写后端:一张 5MB 图片,为什么能撑爆内存?
前端·后端·图片资源
夜之眷属1 小时前
记一次战斗服务器 CPU 打满 100% 且“无法恢复“的排查
java·linux·运维·服务器·后端·性能优化
郝学胜-神的一滴1 小时前
C++ Templates 07:编译报错和调试手段与实战技巧
开发语言·c++·后端·软件工程·visual studio
谢亮_vipxieliang1 小时前
PHP 8 新特性:构造器属性提升与实战
开发语言·后端·php
imDwAaY1 小时前
Spring Boot的核心配置文件一览及其加载顺序
java·spring boot·后端