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. 关注最佳实践
相关推荐
啾啾Fun几秒前
[java基础-JVM篇]1_JVM自动内存管理
java·开发语言·jvm
KuunNNn11 分钟前
蓝桥杯试题:区间次方和(前缀和)
java·蓝桥杯
何中应22 分钟前
Spring Boot延迟执行实现
java·spring boot·后端
一休哥助手25 分钟前
使用 LROPoller 处理 Azure 文档分析时的常见问题及解决方案
后端·python·flask
noravinsc30 分钟前
django models 多条件检索
后端·python·django
B站计算机毕业设计超人1 小时前
计算机毕业设计SpringBoot+Vue.jst网上超市系统(源码+LW文档+PPT+讲解)
vue.js·spring boot·后端·eclipse·intellij-idea·mybatis·课程设计
bing_1581 小时前
Java IO 和 NIO 的基本概念和 API
java·nio
ChinaRainbowSea1 小时前
4. MySQL 逻辑架构说明
java·数据库·sql·mysql·架构
电商数据girl1 小时前
关于酒店旅游信息的数据采集API接口返回||包含参数说明
java·大数据·开发语言·数据库·json·旅游
Ttang231 小时前
JavaWeb基础专项复习4——会话对象Session and Cookie
java·开发语言