java实现一个接口多个实现类,并且依次调用指定方法

接口

package cn.daenx.yhchatsdk.mytest;

public interface MyInterface {
    /**
     * 返回-1,后面的实现类将不再执行
     * 返回0,后面的实现类继续执行
     *
     * @return
     */
    Integer doSomething();
}

实现类

实现类1

package cn.daenx.yhchatsdk.mytest;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

@Service
@Order(2)
public class impl1 implements MyInterface {
    @Override
    public Integer doSomething() {
        System.out.println("执行1");
        return 0;
    }
}

实现类2

package cn.daenx.yhchatsdk.mytest;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

@Service
@Order(1)
public class impl2 implements MyInterface {
    @Override
    public Integer doSomething() {
        System.out.println("执行2");
        return 0;
    }
}

类加载器

package cn.daenx.yhchatsdk.mytest;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;

import java.util.Map;

/**
 * 类加载器
 * 加载所有实现类
 */
public class MyInterfaceLoader {
    public static void load() {
        Map<String, MyInterface> beans = SpringUtil.getContext().getBeansOfType(MyInterface.class);
        for (Map.Entry<String, MyInterface> entry : beans.entrySet()) {
            MyInterface bean = entry.getValue();
            Class<?> clazz = bean.getClass();
            Order order = AnnotationUtils.findAnnotation(clazz, Order.class);
            if (order != null) {
                int value = order.value();
                System.out.println("@Order=" + value);
            }

            // 执行实现类的方法
            Integer integer = bean.doSomething();
            System.out.println("返回值=" + integer);
            // 如果返回值是-1,那么将不再继续执行
            if (integer == -1) {
                break;
            }
        }

    }
}

工具类

package cn.daenx.yhchatsdk.mytest;

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

@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getContext() {
        return applicationContext;
    }
}

测试

@GetMapping("/test")
    public Result test() {
        MyInterfaceLoader.load();
        return Result.ok();
    }

后记

我这里测试是每次都会加载一次所有实现类,你可以弄个全局类,只在启动的时候加载一次即可,自己实现即可~

posted @ 2023-06-12 21:33  DaenMax  阅读(537)  评论(0编辑  收藏  举报