Java获取接口所有实现类的方式

本文对比了Spring容器的ApplicationContext.getBeansOfType()与Java的ServiceLoader在获取接口实现类上的应用,适合已Spring托管的项目和独立服务提供者场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Spring容器实现:ApplicationContext类的getBeansOfType()

Spring作为一个容器,管理着一个项目中所有经过配置的Java类(xml配置文件或Annotation方式)。如果某个接口的所有实现类均被Spring托管了,那么通过Spring就可以很简单的返回这些实现类。

IService是自己写的接口:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ServiceLocator implements ApplicationContextAware{
  /**
   * 用于保存接口实现类名及对应的类
   */
  private Map<String, IService> map;

  /**
   * 获取应用上下文并获取相应的接口实现类
   * @param applicationContext
   * @throws BeansException
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    //根据接口类型返回相应的所有bean
    Map<String, IService> map = applicationContext.getBeansOfType(IService.class);
  }

}

2.ServiceLoader类实现:

ServiceLoader是JDK自带的一个类加载器,位于java.util包当中,作为 A simple service-provider loading facility.

具体使用:
1.在META-INF/services/目录下用你的接口全路径名称命名一个文件(不加后缀),然后在该文件中一行一个添加你的接口实现类的全路径名。
在这里插入图片描述

2.通过load方法来加载出所有的接口实现类:load方法的返回值是一个迭代器,用这个迭代器可以遍历出所有的接口实现类

ServiceLoader<MyInterface> services = ServiceLoader.load(MyInterface.class);

for (MyInterface service : services ) {
                    service .接口的方法(参数);
                }

最后:

以上两种方式,实现的功能都是一样的,实现方式不同,底层用的技术一样的,都是反射。至于选择哪一种,我建议如果项目中的接口实现类都被Spring托管了,那当然是直接用Spring了。如果没有用到Spring的话,那就用ServiceLoader

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值