Spring Core面试题
基础概念
Q1: Spring的核心特性有哪些?
public class SpringCoreBasicDemo { public class IoCExample { public void iocDemo ( ) { @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; } } } } 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生命周期是怎样的?
public class BeanLifecycleDemo { public class BeanDefinitionExample { public void beanDefDemo ( ) { @Component public class LifecycleBean implements InitializingBean , DisposableBean , BeanFactoryAware , BeanNameAware { @Override public void setBeanFactory ( BeanFactory beanFactory) { } @Override public void setBeanName ( String name) { } @PostConstruct public void init ( ) { } @Override public void afterPropertiesSet ( ) { } @PreDestroy public void cleanup ( ) { } @Override public void destroy ( ) { } } } } 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的事务管理是怎样的?
public class TransactionDemo { 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) ) ; } } } } 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的事件机制是怎样的?
public class EventDemo { 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) ) ; } } } } 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的缓存机制是怎样的?
public class CacheDemo { 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) ; } } ; } } } } 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 ( ) { } } } }
}
面试关键点
理解Spring的核心特性 掌握Bean生命周期 熟悉事务管理机制 了解事件处理机制 掌握缓存实现原理 理解AOP的实现 注意性能优化 关注最佳实践