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. 关注最佳实践
相关推荐
数智化转型推荐官31 分钟前
2026统一身份管理系统五大发展趋势解读
java·运维·微服务
看菜鸡互35 分钟前
探索用 SlideML 让大模型生成 PPT 的实验方法
java·运维
IT_陈寒37 分钟前
SpringBoot自动配置不是你以为的那样的智能
前端·人工智能·后端
程序员张32 小时前
SpringBoot集成BCrypt密码加密库
java·spring boot·后端
闲猫2 小时前
Spring AI Agentic 模式(第1部分):Agent Skills——模块化、可复用的能力
java·人工智能·spring
CaffeinePro2 小时前
FastAPI数据库集成SQLAlchemy异步ORM全方案
后端·fastapi
源图客2 小时前
云途物流API开发-鉴权认证(Java)
java·网络·python
小旭Coding2 小时前
凌晨告警轰炸!Go 服务协程只增不减,内存持续暴涨直至 OOM
后端
半个落月3 小时前
用 LangChain.js 手写一个能读写文件和执行命令的 Mini Cursor
javascript·人工智能·后端
liguojun20253 小时前
篮球馆自动计时收费系统:从规则配置到自动结算的全流程拆解
java·大数据·运维·人工智能·物联网·1024程序员节