基于Spring框架的常见应用
以下是基于Spring框架常见应用场景示例,涵盖依赖注入、AOP、事务管理等核心功能,采用模块化分类呈现:
依赖注入(DI)示例
构造器注入
@Service public class UserService { private final UserRepository repository; @Autowired public UserService(UserRepository repository) { this.repository = repository; } }
Setter注入
@Service public class PaymentService { private PaymentGateway gateway; @Autowired public void setGateway(PaymentGateway gateway) { this.gateway = gateway; } }
字段注入(不推荐)
@Service public class OrderService { @Autowired private OrderValidator validator; }
集合注入
@Service public class NotificationService { @Autowired private List<Notifier> notifiers; // 注入多个Notifier实现 }
条件化Bean注入
@Configuration public class AppConfig { @Bean @ConditionalOnProperty(name = "cache.enabled", havingValue = "true") public CacheManager cacheManager() { return new RedisCacheManager(); } }
AOP编程示例
日志切面
@Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logMethodCall(JoinPoint jp) { System.out.println("调用方法: " + jp.getSignature()); } }
性能监控
@Around("@annotation(com.example.MonitorPerformance)") public Object measureTime(ProceedingJoinPoint pjp) throws Throwable { long start = System.currentTimeMillis(); Object result = pjp.proceed(); System.out.println("耗时: " + (System.currentTimeMillis() - start) + "ms"); return result; }
异常重试
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 1000)) public void callExternalApi() { // 可能失败的操作 }
事务管理示例
声明式事务
@Transactional public void transferMoney(Account from, Account to, BigDecimal amount) { from.debit(amount); to.credit(amount); }
事务隔离级别设置
@Transactional(isolation = Isolation.READ_COMMITTED) public List<Order> getRecentOrders() { return orderRepository.findTop10ByOrderByCreateTimeDesc(); }
Web开发示例
REST控制器
@RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { return ResponseEntity.ok(userService.findById(id)); } }
文件上传
@PostMapping("/upload") public String handleUpload(@RequestParam MultipartFile file) { String fileName = fileStorageService.store(file); return "上传成功: " + fileName; }
全局异常处理
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ErrorResponse(ex.getMessage())); } }
数据访问示例
JPA Repository
public interface ProductRepository extends JpaRepository<Product, Long> { List<Product> findByPriceLessThan(BigDecimal price); }
自定义SQL查询
@Query("SELECT p FROM Product p WHERE p.category = :category ORDER BY p.sales DESC") List<Product> findTopSellingByCategory(@Param("category") String category);
分页查询
@GetMapping("/products") public Page<Product> getProducts(Pageable pageable) { return productRepository.findAll(pageable); }
高级特性示例
自定义事件发布
@Service public class OrderService { @Autowired private ApplicationEventPublisher publisher; public void placeOrder(Order order) { publisher.publishEvent(new OrderPlacedEvent(this, order)); } }
定时任务
@Scheduled(cron = "0 0 12 * * ?") public void generateDailyReport() { reportService.generateReport(); }
缓存使用
@Cacheable(value = "products", key = "#id") public Product getProductById(Long id) { return productRepository.findById(id).orElseThrow(); }
多数据源配置
@Configuration @EnableJpaRepositories( basePackages = "com.example.primary", entityManagerFactoryRef = "primaryEntityManager" ) public class PrimaryDataSourceConfig { /* 配置细节 */ }
异步方法调用
@Async public CompletableFuture<User> fetchUserAsync(Long id) { return CompletableFuture.completedFuture(userRepository.findById(id)); }
自定义Validator
@Component public class EmailValidator implements ConstraintValidator<ValidEmail, String> { public boolean isValid(String email, ConstraintValidatorContext context) {