Spring Core面试题

Spring Core面试题

基础概念

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

java 复制代码
public class SpringCoreBasicDemo {
    // 1. IoC容器
    public class IoCExample {
        public void iocDemo() {
            // XML配置
            @Configuration
            public class AppConfig {
                @Bean
                public UserService userService() {
                    return new UserService(userRepository());
                }
                
                @Bean
                public UserRepository userRepository() {
                    return new JdbcUserRepository();
                }
            }
            
            // 注解配置
            @Component
            public class UserService {
                private final UserRepository userRepository;
                
                @Autowired
                public UserService(UserRepository userRepository) {
                    this.userRepository = userRepository;
                }
            }
        }
    }
    
    // 2. AOP实现
    public class AOPExample {
        public void aopDemo() {
            @Aspect
            @Component
            public 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() {
            @Component
            public class LifecycleBean implements 
                InitializingBean, 
                DisposableBean, 
                BeanFactoryAware, 
                BeanNameAware {
                
                @Override
                public void setBeanFactory(BeanFactory beanFactory) {
                    // BeanFactory回调
                }
                
                @Override
                public void setBeanName(String name) {
                    // Bean名称回调
                }
                
                @PostConstruct
                public void init() {
                    // 初始化方法
                }
                
                @Override
                public void afterPropertiesSet() {
                    // 属性设置后回调
                }
                
                @PreDestroy
                public void cleanup() {
                    // 销毁前回调
                }
                
                @Override
                public void destroy() {
                    // 销毁方法
                }
            }
        }
    }
    
    // 2. Bean后处理器
    public class BeanPostProcessorExample {
        public void postProcessorDemo() {
            @Component
            public class CustomBeanPostProcessor 
                implements BeanPostProcessor {
                
                @Override
                public Object postProcessBeforeInitialization(
                    Object bean, String beanName) {
                    if (bean instanceof LifecycleBean) {
                        // 初始化前处理
                    }
                    return bean;
                }
                
                @Override
                public 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
            @EnableTransactionManagement
            public class TransactionConfig {
                @Bean
                public PlatformTransactionManager transactionManager(
                    DataSource dataSource) {
                    return new DataSourceTransactionManager(dataSource);
                }
            }
            
            @Service
            @Transactional
            public 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() {
            @Service
            public 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>() {
                        @Override
                        public 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;
                }
            }
            
            // 事件发布者
            @Service
            public class UserService {
                private final ApplicationEventPublisher eventPublisher;
                
                @Autowired
                public 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() {
            @Component
            public class UserEventListener {
                @EventListener
                public void handleUserCreatedEvent(
                    UserCreatedEvent event) {
                    User user = event.getUser();
                    // 处理用户创建事件
                }
                
                @EventListener
                @Async
                public 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
            @EnableCaching
            public class CacheConfig {
                @Bean
                public CacheManager cacheManager() {
                    SimpleCacheManager cacheManager = 
                        new SimpleCacheManager();
                    cacheManager.setCaches(Arrays.asList(
                        new ConcurrentMapCache("users"),
                        new ConcurrentMapCache("roles")));
                    return cacheManager;
                }
                
                @Bean
                public KeyGenerator keyGenerator() {
                    return new KeyGenerator() {
                        @Override
                        public Object generate(Object target, 
                            Method method, Object... params) {
                            return target.getClass().getSimpleName() + 
                                ":" + method.getName() + 
                                ":" + Arrays.toString(params);
                        }
                    };
                }
            }
        }
    }
    
    // 2. 缓存使用
    public class CacheUsageExample {
        public void cacheUsageDemo() {
            @Service
            public 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. 关注最佳实践
相关推荐
独泪了无痕10 小时前
Spring Data Redis 快速上手
spring boot·redis·后端
wangchunyu11412 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
paopaokaka_luck13 小时前
流浪动物救助与收养系统(DeepSeek AI对话、 ECharts多维分析、救助流程衔接、领养与回访衔接、 捐赠确认与公示、志愿者协作)
java·前端·javascript·人工智能·mysql·echarts·推荐算法
Thomas.Sir13 小时前
第9课:SpringBoot4.x Web开发基础:WebMvc自动配置、静态资源、请求参数接收
java·spring boot
程序 代码狂人13 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
m0_6399069414 小时前
Linux 操作系统入门:目录结构、服务排查常用命令、Shell 脚本基础
linux·运维·后端
2501_9445215914 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
holly就是我15 小时前
AI 编程助手为什么跑偏?用开源 ccglass 看清 Prompt、工具调用和 Token 消耗
人工智能·后端
鸿蒙开发15 小时前
共享 Schema 与 SchemaFactory
前端·后端·harmonyos
用户7884773163415 小时前
小程序后端三选一:云开发、.NET WebAPI、Node,我按客户现状分了三种答案
后端