java获取实现某个接口的所有实现类集合

关键在于: applicationContext.getBeansOfType(ChartService.class);

                  获得Map对象的key为实现类的名称如:chartSimpleServiceImpl

                  获得Map对象的value为实现类对象如: com.read.data.cms.service.impl.ChartExtraServiceImpl@5c85b6e9

applicationContext的获取方法有很多种,我这里暂列两种

第一种方式实现接口所有类集合(注解)

@Autowire
private ApplicationContext applicationContext;


Map<String,ChartService> res = applicationContext.getBeansOfType(ChartService.class);
res.get("实现类的字符串如:chartSimpleServiceImpl")
res.get获得的结果,就是当前实现类对象

第二种方式实现接口所有类集合(实现接口)

/**
 * @author: tianyong
 * @Time: 2019/6/26 11:17
 * @description:服务工厂(主要用于动态注入接口实现类)
 */
@Component
public class ServiceFactory implements ApplicationContextAware {


    //定义成员变量
    private static Map<String,ChartService> res;


    /**
      * @author: tianyong
      * @time: 2019/6/27 16:04
      * @description:设置上下文参数
      */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        res = applicationContext.getBeansOfType(ChartService.class);
    }


    /**
      * @author: tianyong
      * @time: 2019/6/27 16:05
      * @description:根据标记返回当前接口实现类
      */
    public static <T extends ChartService> T getServices(String flag){
        return (T)res.get(flag);
    }



}

如果对您有帮助,麻烦关注本人公众号:周三想吧

在 Spring 容器中,可以通过 `ApplicationContext` 获取实现特定接口的所有 Bean。Spring 提供了 `getBeansOfType` 方法,用于从容器中检索指定类型的所有 Bean,并以 `Map<String, T>` 的形式返回,其中键是 Bean 的名称,值是 Bean 实例。如果只需要 Bean 实例的集合,可以提取值集合并转换为 `List`。 例如,假设有一个接口 `MyService`,其多个实现类被注册为 Spring Bean: ```java public interface MyService { void perform(); } ``` 多个实现类如下: ```java @Service public class MyServiceImpl1 implements MyService { public void perform() { System.out.println("Service 1 performed"); } } @Service public class MyServiceImpl2 implements MyService { public void perform() { System.out.println("Service 2 performed"); } } ``` 在需要获取所有实现类的场景中,可以通过以下方式获取这些 Bean 并转换为 `List`: ```java import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; import java.util.Map; public class BeanListExample { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext("com.example.service"); // 获取所有实现 MyService 接口的 Bean Map<String, MyService> beansMap = context.getBeansOfType(MyService.class); // 提取值集合并转换为 List List<MyService> serviceList = new ArrayList<>(beansMap.values()); // 调用每个 Bean 的 perform 方法 for (MyService service : serviceList) { service.perform(); } } } ``` 通过这种方式,可以方便地获取所有实现特定接口的 Bean,并对它们进行统一处理。此方法利用了 Spring 的 `getBeansOfType` 方法,能够自动识别并返回所有匹配的 Bean 实例[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值