Spring Core面试题

ops/2025/2/26 21:41:30/

Spring Core面试题

基础概念

Q1: Spring的核心特性有哪些?

java">public class SpringCoreBasicDemo {// 1. IoC容器public class IoCExample {public void iocDemo() {// XML配置@Configurationpublic class AppConfig {@Beanpublic UserService userService() {return new UserService(userRepository());}@Beanpublic UserRepository userRepository() {return new JdbcUserRepository();}}// 注解配置@Componentpublic class UserService {private final UserRepository userRepository;@Autowiredpublic UserService(UserRepository userRepository) {this.userRepository = userRepository;}}}}// 2. AOP实现public class AOPExample {public void aopDemo() {@Aspect@Componentpublic class LoggingAspect {@Around("execution(* com.example.service.*.*(..))")public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {String methodName = joinPoint.getSignature().getName();logger.info("Before method: " + methodName);Object result = joinPoint.proceed();logger.info("After method: " + methodName);return result;}@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))",throwing = "ex")public void logException(Exception ex) {logger.error("Exception: " + ex.getMessage());}}}}
}

Q2: Spring的Bean生命周期是怎样的?

java">public class BeanLifecycleDemo {// 1. Bean定义public class BeanDefinitionExample {public void beanDefDemo() {@Componentpublic class LifecycleBean implements InitializingBean, DisposableBean, BeanFactoryAware, BeanNameAware {@Overridepublic void setBeanFactory(BeanFactory beanFactory) {// BeanFactory回调}@Overridepublic void setBeanName(String name) {// Bean名称回调}@PostConstructpublic void init() {// 初始化方法}@Overridepublic void afterPropertiesSet() {// 属性设置后回调}@PreDestroypublic void cleanup() {// 销毁前回调}@Overridepublic void destroy() {// 销毁方法}}}}// 2. Bean后处理器public class BeanPostProcessorExample {public void postProcessorDemo() {@Componentpublic class CustomBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) {if (bean instanceof LifecycleBean) {// 初始化前处理}return bean;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {if (bean instanceof LifecycleBean) {// 初始化后处理}return bean;}}}}
}

高级特性

Q3: Spring的事务管理是怎样的?

java">public class TransactionDemo {// 1. 声明式事务public class DeclarativeTransactionExample {public void transactionDemo() {@Configuration@EnableTransactionManagementpublic class TransactionConfig {@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}}@Service@Transactionalpublic class UserService {@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)public void createUser(User user) {userRepository.save(user);emailService.sendWelcomeEmail(user);}@Transactional(readOnly = true)public User getUser(Long id) {return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException(id));}}}}// 2. 编程式事务public class ProgrammaticTransactionExample {public void programmaticTransactionDemo() {@Servicepublic class UserService {private final PlatformTransactionManager transactionManager;private final UserRepository userRepository;public void createUser(User user) {TransactionTemplate template = new TransactionTemplate(transactionManager);template.execute(new TransactionCallback<Void>() {@Overridepublic Void doInTransaction(TransactionStatus status) {try {userRepository.save(user);emailService.sendWelcomeEmail(user);return null;} catch (Exception ex) {status.setRollbackOnly();throw ex;}}});}}}}
}

Q4: Spring的事件机制是怎样的?

java">public class EventDemo {// 1. 事件定义public class EventDefinitionExample {public void eventDefDemo() {// 自定义事件public class UserCreatedEvent extends ApplicationEvent {private final User user;public UserCreatedEvent(Object source, User user) {super(source);this.user = user;}public User getUser() {return user;}}// 事件发布者@Servicepublic class UserService {private final ApplicationEventPublisher eventPublisher;@Autowiredpublic UserService(ApplicationEventPublisher eventPublisher) {this.eventPublisher = eventPublisher;}public void createUser(User user) {userRepository.save(user);eventPublisher.publishEvent(new UserCreatedEvent(this, user));}}}}// 2. 事件监听public class EventListenerExample {public void eventListenerDemo() {@Componentpublic class UserEventListener {@EventListenerpublic void handleUserCreatedEvent(UserCreatedEvent event) {User user = event.getUser();// 处理用户创建事件}@EventListener@Asyncpublic void handleAsyncEvent(AsyncEvent event) {// 异步处理事件}@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)public void handleTransactionalEvent(TransactionalEvent event) {// 事务提交后处理事件}}}}
}

Q5: Spring的缓存机制是怎样的?

java">public class CacheDemo {// 1. 缓存配置public class CacheConfigExample {public void cacheConfigDemo() {@Configuration@EnableCachingpublic class CacheConfig {@Beanpublic CacheManager cacheManager() {SimpleCacheManager cacheManager = new SimpleCacheManager();cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("users"),new ConcurrentMapCache("roles")));return cacheManager;}@Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method, Object... params) {return target.getClass().getSimpleName() + ":" + method.getName() + ":" + Arrays.toString(params);}};}}}}// 2. 缓存使用public class CacheUsageExample {public void cacheUsageDemo() {@Servicepublic class UserService {@Cacheable(value = "users",key = "#id",condition = "#id != null",unless = "#result == null")public User getUser(Long id) {return userRepository.findById(id).orElse(null);}@CachePut(value = "users",key = "#user.id")public User updateUser(User user) {return userRepository.save(user);}@CacheEvict(value = "users",key = "#id")public void deleteUser(Long id) {userRepository.deleteById(id);}@CacheEvict(value = "users",allEntries = true)public void clearCache() {// 清除所有缓存}}}}
}

面试关键点

  1. 理解Spring的核心特性
  2. 掌握Bean生命周期
  3. 熟悉事务管理机制
  4. 了解事件处理机制
  5. 掌握缓存实现原理
  6. 理解AOP的实现
  7. 注意性能优化
  8. 关注最佳实践

http://www.ppmy.cn/ops/161505.html

相关文章

【LeetCode Hot100】搜索二维矩阵 II[特殊字符]二分查找 vs 线性搜索,Java实现,图解+代码

&#x1f4bb; [LeetCode Hot100] 搜索二维矩阵 II&#x1f525;二分查找 vs 线性搜索&#xff0c;Java实现&#xff0c;图解代码 ✏️本文对应题目链接&#xff1a;搜索二维矩阵 II &#x1f4cc; 题目描述 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 targ…

JavaWeb 学习笔记

前端基础 HTML-CSS <!doctype html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport"content"widthdevice-width, user-scalableno, initial-scale1.0, maximum-scale1.0, minimum-scale1.0…

2025数学建模竞赛汇总,错过再等一年

01、2025第十届数维杯大学生数学建模挑战赛&#xff08;小国赛&#xff09; 竞赛介绍&#xff1a;数学建模行业内仅次于国赛和美赛的的第三赛事&#xff0c;被多所高校认定为国家级二类竞赛。赛题类型是国内唯一和高教社杯国赛题型风格完全一致的全国性数学建模竞赛&#xff0…

WordPress ABF Freight Edition sql注入漏洞复现(CVE-2024-13485)(附脚本)

免责申明: 本文所描述的漏洞及其复现步骤仅供网络安全研究与教育目的使用。任何人不得将本文提供的信息用于非法目的或未经授权的系统测试。作者不对任何由于使用本文信息而导致的直接或间接损害承担责任。如涉及侵权,请及时与我们联系,我们将尽快处理并删除相关内容。 0x0…

javascript-es6 (五)

内置构造函数 在 JavaScript 中 最主要 的数据类型有 6 种&#xff1a; 基本数据类型&#xff1a; 字符串、数值、布尔、undefined、null 引用类型: 对象 但是&#xff0c;我们会发现有些特殊情况&#xff1a; //普通字符串 const str peiqi console.log(str.length) //…

深入理解 JSP 与 Servlet:原理、交互及实战应用

一、引言 在 Java Web 开发领域,JSP(JavaServer Pages)和 Servlet 是两个至关重要的技术,它们共同构成了动态网页开发的基础。Servlet 作为服务器端的 Java 程序,负责处理客户端请求并生成响应;而 JSP 则是一种简化的 Servlet 开发方式,允许开发者在 HTML 页面中嵌入 J…

Orcale、MySQL中左连接,右连接,内连接的区别以及运用场景系列04(运用场景、左右表关系)

1. 总结 Oracle 连接类型区别运用场景左右表关系适用性ON与WHERE条件相关内连接&#xff08;INNER JOIN&#xff09;仅返回两个表中满足连接条件的行&#xff0c;不满足条件的行不会出现在结果集中。例如&#xff0c;若有employees表和departments表&#xff0c;仅返回两表中…

蓝桥备赛(一)- C++入门(上)

一、工具安装 Dev-C安装&#xff1a;https://www.bilibili.com/video/BV1kC411G7CS 一般比赛会用到Dev-C, 但是Dev-C还是有自身的局限性 &#xff0c; 后续的博客学习中 &#xff0c; 必要的时候 &#xff0c; 会使用VS2022 &#xff0c; 下面是VS2022的安装和使用教程。 VS202…