Spring框架下的中医针灸系统实现

发布于:2025-08-05 ⋅ 阅读:(15) ⋅ 点赞:(0)

基于Spring框架的常见应用

以下是基于Spring框架常见应用场景示例,涵盖依赖注入、AOP、事务管理等核心功能,采用模块化分类呈现:

依赖注入(DI)示例

  1. 构造器注入

    @Service
    public class UserService {
        private final UserRepository repository;
        @Autowired
        public UserService(UserRepository repository) {
            this.repository = repository;
        }
    }
    
  2. Setter注入

    @Service
    public class PaymentService {
        private PaymentGateway gateway;
        @Autowired
        public void setGateway(PaymentGateway gateway) {
            this.gateway = gateway;
        }
    }
    
  3. 字段注入(不推荐)

    @Service
    public class OrderService {
        @Autowired
        private OrderValidator validator;
    }
    
  4. 集合注入

    @Service
    public class NotificationService {
        @Autowired
        private List<Notifier> notifiers; // 注入多个Notifier实现
    }
    
  5. 条件化Bean注入

    @Configuration
    public class AppConfig {
        @Bean
        @ConditionalOnProperty(name = "cache.enabled", havingValue = "true")
        public CacheManager cacheManager() {
            return new RedisCacheManager();
        }
    }
    

AOP编程示例

  1. 日志切面

    @Aspect
    @Component
    public class LoggingAspect {
        @Before("execution(* com.example.service.*.*(..))")
        public void logMethodCall(JoinPoint jp) {
            System.out.println("调用方法: " + jp.getSignature());
        }
    }
    
  2. 性能监控

    @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;
    }
    
  3. 异常重试

    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public void callExternalApi() {
        // 可能失败的操作
    }
    

事务管理示例

  1. 声明式事务

    @Transactional
    public void transferMoney(Account from, Account to, BigDecimal amount) {
        from.debit(amount);
        to.credit(amount);
    }
    
  2. 事务隔离级别设置

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public List<Order> getRecentOrders() {
        return orderRepository.findTop10ByOrderByCreateTimeDesc();
    }
    

Web开发示例

  1. REST控制器

    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        @GetMapping("/{id}")
        public ResponseEntity<User> getUser(@PathVariable Long id) {
            return ResponseEntity.ok(userService.findById(id));
        }
    }
    
  2. 文件上传

    @PostMapping("/upload")
    public String handleUpload(@RequestParam MultipartFile file) {
        String fileName = fileStorageService.store(file);
        return "上传成功: " + fileName;
    }
    
  3. 全局异常处理

    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(ResourceNotFoundException.class)
        public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ErrorResponse(ex.getMessage()));
        }
    }
    

数据访问示例

  1. JPA Repository

    public interface ProductRepository extends JpaRepository<Product, Long> {
        List<Product> findByPriceLessThan(BigDecimal price);
    }
    
  2. 自定义SQL查询

    @Query("SELECT p FROM Product p WHERE p.category = :category ORDER BY p.sales DESC")
    List<Product> findTopSellingByCategory(@Param("category") String category);
    
  3. 分页查询

    @GetMapping("/products")
    public Page<Product> getProducts(Pageable pageable) {
        return productRepository.findAll(pageable);
    }
    

高级特性示例

  1. 自定义事件发布

    @Service
    public class OrderService {
        @Autowired
        private ApplicationEventPublisher publisher;
        
        public void placeOrder(Order order) {
            publisher.publishEvent(new OrderPlacedEvent(this, order));
        }
    }
    
  2. 定时任务

    @Scheduled(cron = "0 0 12 * * ?")
    public void generateDailyReport() {
        reportService.generateReport();
    }
    
  3. 缓存使用

    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        return productRepository.findById(id).orElseThrow();
    }
    
  4. 多数据源配置

    @Configuration
    @EnableJpaRepositories(
        basePackages = "com.example.primary",
        entityManagerFactoryRef = "primaryEntityManager"
    )
    public class PrimaryDataSourceConfig { /* 配置细节 */ }
    
  5. 异步方法调用

    @Async
    public CompletableFuture<User> fetchUserAsync(Long id) {
        return CompletableFuture.completedFuture(userRepository.findById(id));
    }
    
  6. 自定义Validator

    @Component
    public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
        public boolean isValid(String email, ConstraintValidatorContext context) {
         

网站公告

今日签到

点亮在社区的每一天
去签到