Spring Core面试题

devtools/2025/2/27 11:52:32/

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/devtools/163053.html

相关文章

MAC 怎么设置 Java虚拟内存设置

在 macOS 中设置 Java 虚拟内存&#xff08;即 JVM 的堆内存大小&#xff09;需要通过 Java 虚拟机参数来调整。以下是具体的操作步骤和常见场景的配置方法&#xff1a; 1. 理解 JVM 内存参数 Java 虚拟机的内存管理主要通过以下参数控制&#xff1a; -Xms: 初始堆内存大小&a…

DPVS-5: 后端服务监控原理与测试

后端监控原理 被动监测 DPVS自带了被动监控&#xff0c;通过监控后端服务对外部请求的响应情况&#xff0c;判断服务器是否可用。 DPVS的被动监测&#xff0c;并不能获取后端服务器的详细情况&#xff0c;仅仅通过丢包/拒绝情况来发觉后端服务是否可用。 TCP session state…

H5 火柴人科目三和GitHub获取仓库点星星的用户列表发生了艺术的碰撞

先看效果&#xff0c;代码写的比较乱&#xff0c;有待优化 效果 https://linyisonger.github.io/H5.Examples/?name./089.%E7%9C%8B%E6%98%9F%E6%98%9F%E7%9A%84%E8%88%9E%E8%80%85.html 思路 看起来很简单&#xff0c;实则也不是很难&#xff0c;就是需要思路要打开。 一…

MailKit: 在 .NET 中实现高效电子邮件发送与接收

CsvHelper 是一个用于处理 CSV 文件的 .NET 库&#xff0c;能够简化 CSV 文件的读写操作&#xff0c;尤其是在处理复杂的数据结构时。支持快速、灵活且易于使用的读取和写入操作&#xff0c;并且完全免费用于商业用途。 1. 安装 第一步&#xff0c;老规矩&#xff0c;先安装 …

矩阵的 正定(Positive Definite)与负定(Negative Definite):从Fisher信息矩阵看“曲率”的秘密

矩阵的正定与负定&#xff1a;从Fisher信息矩阵看“曲率”的秘密 在数学和统计学中&#xff0c;矩阵的“正定性”和“负定性”是一对重要概念&#xff0c;尤其在优化、统计推断和机器学习中频繁出现。比如&#xff0c;Fisher信息矩阵&#xff08;Fisher Information Matrix, F…

深入理解 并查集LRUCaChe

并查集&LRUCaChe 个人主页&#xff1a;顾漂亮 文章专栏&#xff1a;Java数据结构 1.并查集的原理 在一些应用问题中&#xff0c;需要将n个不同的元素划分成一些不相交的集合。开始时&#xff0c;每个元素自成一个单元素集合&#xff0c;然后根据一定规律将归于同一组元素的…

【0010】HTML水平线标签详解

如果你觉得我的文章写的不错&#xff0c;请关注我哟&#xff0c;请点赞、评论&#xff0c;收藏此文章&#xff0c;谢谢&#xff01; 本文内容体系结构如下&#xff1a; 一、水平线标签概述 在HTML中&#xff0c;<hr>标签用于在网页上插入一条水平线&#xff0c;其主要…

网络安全复习资料

网络安全复习资料 1.计算机网络安全是指保持网络中的硬件、软件系统正常运行&#xff0c;使他们不因自然和人为的因素而受到破坏、更改和泄露。 2.网络安全&#xff1a;物理安全&#xff0c;软件安全&#xff0c;信息安全&#xff0c;运行安全。 3.安全防范措施&#xff1a…