Spring面试18问:深度解析与实战指南
2025.09.18 11:35浏览量:0简介:本文围绕Spring框架面试中常见的18个核心问题展开,涵盖基础概念、核心组件、高级特性及最佳实践,帮助开发者系统梳理知识体系,提升面试竞争力。
一、基础概念篇
1. Spring的核心特性是什么?
Spring框架的核心优势在于控制反转(IoC)和面向切面编程(AOP)。IoC通过容器管理对象生命周期,解耦组件依赖;AOP则通过动态代理实现横切关注点(如日志、事务)的模块化。例如,使用@Autowired
注解实现依赖注入,替代手动new
对象的方式。
2. Bean的作用域有哪些?
Spring支持五种作用域:
- Singleton(默认):每个容器仅一个实例。
- Prototype:每次请求创建新实例。
- Request:仅适用于Web应用,每个HTTP请求一个实例。
- Session:每个HTTP会话一个实例。
- Application:ServletContext生命周期内唯一实例。
配置示例:
@Bean
@Scope("prototype")
public MyService myService() {
return new MyService();
}
3. 依赖注入的三种方式
- 构造器注入:推荐方式,确保不可变性和显式依赖。
@Service
public class UserService {
private final UserRepository repository;
@Autowired
public UserService(UserRepository repository) {
this.repository = repository;
}
}
- Setter注入:适用于可选依赖。
- 字段注入:简洁但测试困难,不推荐在生产代码中使用。
二、核心组件篇
4. Spring MVC的工作流程
- 客户端发送请求至
DispatcherServlet
。 HandlerMapping
确定对应的Controller
。Controller
处理请求并返回ModelAndView
。ViewResolver
解析视图名称并渲染响应。
关键注解:
@Controller
:标记处理类。@RequestMapping
:映射URL路径。@ResponseBody
:直接返回数据(如JSON)。
5. Spring Data JPA的核心接口JpaRepository
继承自CrudRepository
,提供:
- 基本CRUD操作(如
save()
、findById()
)。 - 分页查询(
Page<T> findAll(Pageable pageable)
)。 - 自定义查询方法(通过方法名派生查询)。
示例:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name); // 方法名派生查询
}
6. AOP的实现原理
Spring AOP基于动态代理:
- JDK动态代理:适用于接口。
- CGLIB代理:适用于类(通过继承实现)。
切面配置示例:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Method called: " + joinPoint.getSignature());
}
}
三、高级特性篇
7. 事务传播行为有哪些?
REQUIRED
(默认):加入当前事务,若无则新建。REQUIRES_NEW
:总是新建事务,挂起当前事务。SUPPORTS
:支持当前事务,若无则以非事务方式执行。
配置示例:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void updateUser(User user) {
// 业务逻辑
}
8. Spring Boot自动配置原理
通过@EnableAutoConfiguration
注解触发,依赖spring-boot-autoconfigure
模块中的META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件,按条件(如类路径存在)加载配置类。
9. 自定义Starter的步骤
- 创建模块并添加
spring-boot-autoconfigure
依赖。 - 编写自动配置类(使用
@Conditional
注解)。 - 在
resources/META-INF
下创建spring.factories
文件,指定自动配置类。
四、性能与安全篇
10. 缓存抽象的使用
Spring支持@Cacheable
、@CacheEvict
等注解,集成Ehcache、Redis等实现。
示例:
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
// 数据库查询
}
11. 防止XSS攻击
- 使用
Spring Security
的CsrfFilter
。 - 在Thymeleaf模板中启用自动转义:
<div th:utext="${userInput}"></div> <!-- 不安全 -->
<div th:text="${userInput}"></div> <!-- 安全 -->
12. 异步任务与定时任务
- 异步任务:
@Async
注解 + 配置@EnableAsync
。 - 定时任务:
@Scheduled
注解(需@EnableScheduling
)。
示例:
@Scheduled(cron = "0 0 * * * ?")
public void scheduledTask() {
// 定时执行
}
五、最佳实践篇
13. 循环依赖的解决方案
- 构造器注入:直接抛出异常。
- Setter/字段注入:通过三级缓存(单例对象池、原型对象池、单例工厂)解决。
14. 测试Spring应用的技巧
- 使用
@SpringBootTest
加载完整上下文。 - 模拟依赖:
@MockBean
注解。 - 测试切片:
@WebMvcTest
(仅测试Controller层)。
15. 监控Spring应用
- Actuator端点:
/health
、/metrics
。 - 集成Prometheus + Grafana实现可视化监控。
六、常见问题篇
16. @RestController
与@Controller
的区别
@Controller
:返回视图名称,需配合@ResponseBody
返回数据。@RestController
:等价于@Controller + @ResponseBody
,直接返回数据。
17. 如何解决NoUniqueBeanDefinitionException
?
- 使用
@Qualifier
指定Bean名称。 - 优先使用构造器注入并标记
@Primary
。
18. Spring Cloud与Spring Boot的关系
Spring Boot是快速构建独立应用的框架,Spring Cloud基于Spring Boot提供分布式系统工具(如服务发现、配置中心)。
总结
本文系统梳理了Spring面试中的高频问题,涵盖从基础到高级的核心知识点。建议读者结合实际项目经验,深入理解IoC、AOP、事务管理等核心机制,并掌握Spring Boot自动化配置与Spring Cloud微服务架构。面试前可通过编写Demo代码验证理论,提升实战能力。
发表评论
登录后可评论,请前往 登录 或 注册