如何根据具体设备类型动态注入对应的 API 服务实现

小浩小哥_4441

小浩小哥_4441

2026-06-05

724人浏览

原创

如何根据具体设备类型动态注入对应的 API 服务实现

本文介绍在 Spring 中如何为泛型接口 ApiService 的多种具体实现(如 ImouService、DahuaService)实现运行时按实际设备子类类型自动路由调用,避免 Bean 注入歧义,并确保 getDeviceSnap() 被正确分发到匹配的实现类。

本文介绍在 spring 中如何为泛型接口 `apiservice` 的多种具体实现(如 `imouservice`、`dahuaservice`)实现运行时按实际设备子类类型自动路由调用,避免 bean 注入歧义,并确保 `getdevicesnap()` 被正确分发到匹配的实现类。

在 Spring 应用中,当多个 @Service 类实现同一个泛型接口(如 ApiService 和 ApiService)时,直接按接口类型 ApiService 注入会导致 Spring 无法确定应选择哪一个 Bean,从而抛出 NoUniqueBeanDefinitionException(“2 beans found”)。根本原因在于:Spring 的依赖注入是静态的、编译期绑定的,它不感知泛型的实际类型参数(即 T 的具体运行时类),也无法自动根据 basicDevice.getClass() 去匹配对应的服务实现。

✅ 正确解法不是「按类型注入单个 Bean」,而是注入所有实现的集合,再结合运行时类型判断进行动态分发:

@Service
public class ScheduleTask {

    private final DeviceVehicleRepository deviceVehicleRepository;
    private final UrlDeviceBeanRepository urlDeviceBeanRepository;
    private final Collection<apiservice>> apiServices; // ✅ 注入所有 ApiService 实现
    private final S3Service service;
    private final CacheManager cacheManager;

    public ScheduleTask(DeviceVehicleRepository deviceVehicleRepository,
                        UrlDeviceBeanRepository urlDeviceBeanRepository,
                        Collection<apiservice>> apiServices, // 注意:此处是 Collection,非单个
                        S3Service service,
                        CacheManager cacheManager) {
        this.deviceVehicleRepository = deviceVehicleRepository;
        this.urlDeviceBeanRepository = urlDeviceBeanRepository;
        this.apiServices = apiServices;
        this.service = service;
        this.cacheManager = cacheManager;
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void getSnaps() {
        Long timestamp = Instant.now().getEpochSecond();
        log.info("Started scheduled task to get snapshots");

        List<basicdevice> allVehiclesWithDevices = (List<basicdevice>) deviceVehicleRepository.findAll();
        allVehiclesWithDevices.parallelStream().forEach(basicDevice -> {
            byte[] contentBytes = dispatchToMatchingService(basicDevice);
            if (contentBytes != null && contentBytes.length > 0) {
                urlDeviceBeanRepository.save(new UrlDeviceBean(contentBytes,
                        basicDevice.getVehicleId(), timestamp));
            }
        });
    }

    // 核心逻辑:根据 basicDevice 的实际运行时类型,查找匹配的 ApiService 实现
    private byte[] dispatchToMatchingService(BasicDevice device) {
        Class> deviceClass = device.getClass();
        return apiServices.stream()
                .filter(service -> {
                    // 获取 ApiService<t> 中 T 的实际类型(需在实现类中保留泛型信息)
                    Type genericInterface = Arrays.stream(service.getClass().getInterfaces())
                            .filter(t -> t instanceof ParameterizedType &&
                                    ((ParameterizedType) t).getRawType().equals(ApiService.class))
                            .findFirst()
                            .orElse(null);
                    if (genericInterface instanceof ParameterizedType) {
                        Type actualTypeArg = ((ParameterizedType) genericInterface).getActualTypeArguments()[0];
                        if (actualTypeArg instanceof Class) {
                            return ((Class>) actualTypeArg).isAssignableFrom(deviceClass);
                        }
                    }
                    return false;
                })
                .findFirst()
                .map(service -> {
                    try {
                        // 利用反射安全调用泛型方法(因编译期擦除,需强制转型)
                        Method method = service.getClass().getMethod("getDeviceSnap", device.getClass());
                        return (byte[]) method.invoke(service, device);
                    } catch (Exception e) {
                        log.error("Failed to invoke getDeviceSnap for device: {}", device.getClass().getSimpleName(), e);
                        return new byte[0];
                    }
                })
                .orElse(new byte[0]);
    }
}</t></basicdevice></basicdevice></apiservice></apiservice>

⚠️ 关键注意事项:

有道速读
有道速读

有道速读是一款AI论文写作工具,网易有道推出的AI论文和文档阅读助手。

下载
  • Collection> 是 Spring 自动注入所有 ApiService 子类型的 Bean(无论泛型参数为何),前提是它们被正确标记为 @Service 且在组件扫描路径下。
  • 上述 dispatchToMatchingService 使用了反射获取泛型实参并做 isAssignableFrom 匹配,这是保障类型安全路由的核心。若追求更高性能与可维护性,建议为每个 ApiService 实现添加一个 supports(Class> deviceType) 方法,由实现类显式声明支持的设备类型(例如 return ImouDevice.class.isAssignableFrom(deviceType);),从而避免反射开销。
  • 所有 BasicDevice 子类(如 ImouDevice、DahuaDevice)必须被 JPA 正确识别(已通过 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 配置),确保从数据库查询时能返回具体子类实例,而非仅 BasicDevice 父类代理对象。

? 进阶建议:可进一步封装为 ApiServiceRegistry 组件,内置缓存映射(Class extends BasicDevice> → ApiService),提升高频调用下的性能与可测试性。

通过该方案,你无需修改现有服务实现,即可实现「一个设备实例,自动命中唯一适配的服务实现」,真正达成策略模式 + 泛型 + Spring 容器的优雅协同。

大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

2025.08.06

2411

22

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

2026.01.26

437

25

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

2023.09.05

591

5

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

2023.10.12

1455

7

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

2025.08.19

4526

10

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

2025.12.22

436

5

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

2025.12.24

620

18

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

2026.02.11

385

24

Kotlin协程编程与Spring Boot集成实践
Kotlin协程编程与Spring Boot集成实践

本专题围绕 Kotlin 协程机制展开,深入讲解挂起函数、协程作用域、结构化并发与异常处理机制,并结合 Spring Boot 展示协程在后端开发中的实际应用。内容涵盖异步接口设计、数据库调用优化、线程资源管理以及性能调优策略,帮助开发者构建更加简洁高效的 Kotlin 后端服务架构。

2026.02.12

351

18

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.6万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 133.4万人学习