当前位置: 首页 > news >正文

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

基于Spring框架的常见应用

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

依赖注入(DI)示例

  1. 构造器注入

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

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

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

    @Service
    public class NotificationService {@Autowiredprivate 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 {@Autowiredprivate 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) {
http://www.lryc.cn/news/606661.html

相关文章:

  • 使用uniapp开发小程序-【引入字体并全局使用】
  • 1.6万 Star 的流行容器云平台停止开源
  • GitHub 趋势日报 (2025年07月31日)
  • hadoop.yarn 带时间的LRU 延迟删除
  • 【实战】Dify从0到100进阶--插件开发(1)Github爬取插件
  • 【2025/08/01】GitHub 今日热门项目
  • 24 SAP CPI 调用SAP HTTP接口
  • R语言基础图像及部分调用函数
  • Dify API接口上传文件 postman配置
  • osloader!DoGlobalInitialization函数分析之HW_CURSOR--NTLDR源代码分析之设置光标
  • django操作orm整套
  • 学习设计模式《二十》——解释器模式
  • 如何使用Postman做接口测试
  • curl命令使用
  • 【机器学习与数据挖掘实战 | 医疗】案例20:基于交叉验证和LightGBM算法的糖尿病遗传风险预测
  • 机器学习②【字典特征提取、文本特征处理(TF-IDF)、数据标准化与归一化、特征降维】
  • 解决IDEA无法克隆GitHub上的工程的问题
  • 解决IDEA中MAVEN项目总是将LANGUAGE LEVEL重置的问题
  • SSL 剥离漏洞
  • 把上次做的图片的API改成国内版,让图片返回速度提升一个档次
  • 对于前端闭包的详细理解
  • LeetCode热题100——146. LRU 缓存
  • Typora v1.10.8 好用的 Markdown 编辑器
  • Linux 系统监控脚本实战:磁盘空间预警、Web 服务与访问测试全流程
  • ACM SIGCOMM 2024论文精选-01:5G【Prism5G】
  • 数据处理--生成Excel文档
  • 18.若依框架中的xss过滤器
  • 南太平洋金融基建革命:斐济-巴新交易所联盟的技术破局之路 ——从关税动荡到离岸红利,跨境科技如何重塑太平洋资本生态
  • 基于html,css,jquery,django,lstm,cnn,tensorflow,bert,推荐算法,mysql数据库
  • 元策联盈:深耕金融领域,赋能行业发展​