Spring Core面试题

server/2025/2/28 23:07:01/

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/server/171406.html

相关文章

Nmap使用指南

Nmap使用指南 Nmap (网络映射器) 是一款强大的应用网络扫描和安全核查工具&#xff0c;适合于网络管理和安全专家。本文将介绍Nmap的基本使用方法&#xff0c;包括基本命令和常用功能。 1. 基本使用方式 Nmap的基本命令格式如下&#xff1a; nmap [选项] 目标地址目标地址 可…

火狐浏览器多开指南:独立窗口独立IP教程

无论是跨境电商从业者需要管理多个店铺账号&#xff0c;还是海外社交媒体营销人员要运营多个社交平台账号&#xff0c;亦或是从事多账号广告投放的人员&#xff0c;都面临着一个共同的挑战 —— 如何高效管理多个账号&#xff0c;并确保每个账号的独立性。 在这种情况下&#…

蓝牙接近开关模块感应开锁手机靠近解锁支持HID低功耗

ANS-BT101M是安朔科技推出的蓝牙接近开关模块&#xff0c;低功耗ble5.1&#xff0c;采用UART通信接口&#xff0c;实现手机自动无感连接&#xff0c;无需APP&#xff0c;人靠近车门自动开锁&#xff0c;支持苹果、安卓、鸿蒙系统&#xff0c;也可以通过手机手动开锁或上锁&…

12. 三昧真火焚环劫 - 环形链表检测(快慢指针)

哪吒在数据修仙界中继续他的修炼之旅。这一次,他来到了一片神秘的环形山脉,山脉中有一条蜿蜒的火龙,它象征着环形链表。山脉的入口处有一块巨大的石碑,上面刻着一行文字:“欲破此山,需以三昧真火之力,焚环劫之链,快慢指针定环踪。” 哪吒定睛一看,石碑上还有一行小字…

矩阵营销的 AI 进化:DeepSeek 如何助力批量运营账号?

在数字营销的浪潮中&#xff0c;矩阵营销 已成为企业拓展市场、提升曝光的重要策略。然而&#xff0c;面对日益复杂的流量生态和平台风控&#xff0c;如何高效运营海量账号&#xff0c;同时保持内容的原创性和高转化率&#xff0c;成为营销人员的一大挑战。 随着 DeepSeek AI …

山东大学软件学院nosql实验二

实验二 熟悉环境、建立/删除表、插入数据 实验内容&#xff1a; 创建命名空间&#xff08;user学号&#xff0c;例如user201500300001&#xff09;&#xff0c;设计表结构并创建表&#xff0c;将附件数据插入。 实验步骤与内容&#xff1a; 方法一&#xff1a; 对于csv文…

验证码介绍及生成与验证(HTML + JavaScript实现)

验证码介绍及生成与验证&#xff08;HTML JavaScript实现&#xff09; 验证码 验证码&#xff08;全自动区分计算机和人类的图灵测试&#xff0c;‌CAPTCHA &#xff0c;C‌ompletely ‌A‌utomated ‌P‌ublic ‌T‌uring test to tell ‌C‌omputers and ‌H‌umans ‌A‌…

GDidees CMS v3.9.1本地文件泄露漏洞(CVE-2023-27179)

漏洞简介&#xff1a; GDidees CMS v3.9.1及更低版本被发现存在本地文件泄露漏洞&#xff0c;漏洞通过位于 /_admin/imgdownload.php 的 filename 参数进行利用。 漏洞环境&#xff1a; 春秋云镜中的漏洞靶标&#xff0c;CVE编号为CVE-2023-27179 漏洞复现: 进入靶场发现没…