使用Java自定义注解和反射机制实现业务的多态

一、多态的实现方式

本文主要是使用自定义注解和反射机制,满足多业务的实现上的多态。

二、类的设计

image.png
image.png

三、自定义注解

3.1、类的实现

注意,这里增加了spring boot 的注解@Component,是为后期加载到spring容器里。

import org.springframework.stereotype.Component;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 标识端点类,类似springboot中@RestController的作用,
 * 已组合@Component,在springboot启动时将自动创建端点类的单例实例
 * 每个不同的应用id仅允许存在一个端点类,若有重复的应用Id,启动扫描将抛出错误并终止进程
 * 每个端点类中,除@OnCommand之外的每个端点仅允许使用一次,若一个端点类中有重复使用的端点,启动扫描将抛出错误并终止进程
 * 每个端点类中,可使用多个@OnCommand注解,但它的value值,即cmd,必须唯一,若一个端点类中有value重复的@OnCommand端点,启动扫描将抛出错误并终止进程
 *
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface Endpoints {
    String appId() default "";
}

3.2、方法的重写

这里自定义了两个方法注解,在实现类的方法加上它即实现方法的重写。类似,接口和实现类的方法重写。

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OnOpen {
    String value() default "";

    String appId() default "";

    String endpointName() default "onOpen";
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OnClose {
    String value() default "";

    String appId() default "";

    String endpointName() default "onClose";
}

四、定义接口

import com.xxx.ws.test.service.dto.RequestContent;

public interface EndpointService {

    void doOnOpen(RequestContent requestContent);

    void doOnClose(RequestContent requestContent);
}

五、接口的实现

5.1、default默认实现

@Slf4j
@Endpoints(appId = "default")
public class DefaultEndpointImpl {
    @OnOpen
    public void onOpen(String message) {
        log.info("default onOpen方法{}", message);
    }

    @OnClose
    public void onClose(String message) {
        log.info("default onClose方法{}", message);
    }
}

5.2、admin业务的实现

@Slf4j
@Endpoints(appId = "admin")
public class AdminEndpointImpl {
    @OnOpen
    public void onOpen(String message) {
        log.info("admin onOpen方法{}", message);
    }

    @OnClose
    public void onClose(String message) {
        log.info("admin onClose方法{}", message);
    }
}

六、端点注册

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自动遍历所有的带@Endpoints注解的类,对每个端点进行注册
 */
@Slf4j
@Component
public class EndpointRegistry extends ApplicationObjectSupport {

    private ConcurrentHashMap<String, Method> methodMapper = new ConcurrentHashMap<>();

    private ConcurrentHashMap<String, Object> instanceMapper = new ConcurrentHashMap<>();

    private static final String METHOD_FORMAT_STR = "%s-%s";

    private static final String ON_OPEN = "onOpen";
    private static final String ON_CLOSE = "onClose";

    public Object getEndpointInstance(String instanceKey) {
        if (StringUtils.isEmpty(instanceKey)) {
            return null;
        }
        Object instance = instanceMapper.get(instanceKey);
        return instance;
    }

    public Method getOnOpen(String appId) {
        return getMethod(ON_OPEN, appId);
    }

    public Method getOnClose(String appId) {
        return getMethod(ON_CLOSE, appId);
    }

    /**
     * 应用初始化的时候加载
     */
    @PostConstruct
    public void init() {
        ApplicationContext context = getApplicationContext();
        try {
            // 找出所有@Endpoints注解的,需要注册端点的类的名称
            String[] endpointBeanNames = context.getBeanNamesForAnnotation(Endpoints.class);
            Set<Class<?>> endpointClasses = new HashSet<>(endpointBeanNames.length);
            // 获取每个类的Class,后面需要遍历类内方法
            for (String beanName : endpointBeanNames) {
                endpointClasses.add(context.getType(beanName));
            }
            for (Class<?> endpointClass : endpointClasses) {
                // 注册每一个类内的端点
                registerEndpoints(context, endpointClass);
            }
        } catch (Exception e) {
            log.error("endpoints init Error!", e);
            System.exit(0);
        }
    }

    private void registerEndpoints(ApplicationContext context, Class<?> endpointClass) {
        Class currentClazz = endpointClass;
        while (!currentClazz.equals(Object.class)) {
            // 若当前类没有@Endpoints注解,则跳过,继续遍历其父类
            if (!currentClazz.isAnnotationPresent(Endpoints.class)) {
                currentClazz = currentClazz.getSuperclass();
                continue;
            }
            // 从该类的Endpoints注解中获取appId
            Endpoints endpoints = (Endpoints) currentClazz.getDeclaredAnnotation(Endpoints.class);
            String appId = endpoints.appId();

            // appId不允许重复
            if (instanceMapper.containsKey(appId)) {
                throw new IllegalStateException(String.format("exist duplicated appId: [%s]", appId));
            } else {
                Object bean = context.getAutowireCapableBeanFactory().getBean(currentClazz);
                if (null != bean) {
                    instanceMapper.put(appId, bean);
                } else {
                    log.warn(String.format("no bean instance can be found: [%s][%s]", appId, currentClazz.getName()));
                }
            }
            // 获取类中所有的方法列表
            Method[] methods = currentClazz.getDeclaredMethods();
            // 检查每一个方法,注册类内的所有端点
            this.registerMethods(methods, appId);
            // 遍历该类的所有父类,查询是否有覆盖的方法,若检查父类已是Object时,结束遍历
            currentClazz = currentClazz.getSuperclass();
        }
    }

    private void registerMethods(Method[] methods, String appId) {
        for (Method method : methods) {
            // 仅注册含有自定义注解的方法
            if (method.getAnnotation(OnOpen.class) != null) {
                this.registerMethod(method,
                        assembleMethodKey(method.getAnnotation(OnOpen.class).endpointName(), appId));
            } else if (method.getAnnotation(OnClose.class) != null) {
                this.registerMethod(method,
                        assembleMethodKey(method.getAnnotation(OnClose.class).endpointName(), appId));
            }
        }
    }

    private void registerMethod(Method method, String endpointName) {
        // 若该方法不是public方法,抛出方法不是public错误
        this.checkPublic(method);

        // 若已存在,且已存在方法与当前方法不是Override关系时,抛出端点重复定义错误
        if (methodMapper.containsKey(endpointName)) {
            if (!isMethodOverride(method, methodMapper.get(endpointName))) {
                Method existMethod = methodMapper.get(endpointName);
                throw new IllegalArgumentException(
                        String.format("endpoint method duplicated : [%s][%s] conflicts with [%s][%s]",
                                method.getDeclaringClass().getName(),
                                method.getName(),
                                existMethod.getDeclaringClass().getName(),
                                existMethod.getName()));
            }
        } else {
            // 未注册过,则注册
            methodMapper.put(endpointName, method);
        }
    }

    private void checkPublic(Method m) {
        if (!Modifier.isPublic(m.getModifiers())) {
            throw new IllegalStateException(String.format(
                    "method access denied: method not public [%s][%s]",
                    m.getDeclaringClass().getName(),
                    m.getName()));
        }
    }

    private boolean isMethodOverride(Method method1, Method method2) {
        return (method1.getName().equals(method2.getName())
                && method1.getReturnType().equals(method2.getReturnType())
                && Arrays.equals(method1.getParameterTypes(), method2.getParameterTypes()));
    }

    private Method getMethod(String endpointName, String appId) {
        return methodMapper.get(assembleMethodKey(endpointName, appId));
    }

    /**
     * {appId}-{端点类型},如:admin-onOpen
     *
     * @param endpointName onOpen
     * @param appId        admin
     * @return
     */
    private String assembleMethodKey(String endpointName, String appId) {
        return String.format(METHOD_FORMAT_STR, appId, endpointName);
    }
}

七、端点Endpoint的工厂类

import com.xxx.ws.test.service.dto.RequestContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

@Slf4j
@Service
public class EndpointServiceFactory implements EndpointService {

    @Autowired
    private EndpointRegistry endpointRegistry;

    @Override
    public void doOnOpen(RequestContent requestContent) {
        String appId = requestContent.getAppId();

        // 获取应用ID对应的类和方法
        Object instance = endpointRegistry.getEndpointInstance(appId);
        Method onOpen = endpointRegistry.getOnOpen(appId);

        try {
            onOpen.invoke(instance, requestContent.getMessage());
        } catch (Exception e) {
            log.error("出现异常", e);
        }
    }

    @Override
    public void doOnClose(RequestContent requestContent) {
        String appId = requestContent.getAppId();

        // 获取应用ID对应的类和方法
        Object instance = endpointRegistry.getEndpointInstance(appId);
        Method onOpen = endpointRegistry.getOnClose(appId);

        try {
            onOpen.invoke(instance, requestContent.getMessage());
        } catch (Exception e) {
            log.error("出现异常", e);
        }
    }
}

  • RequestContent.java请求上下文
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class RequestContent {
   /**
    * 应用类型
    */
   private String appId;

   /**
    * 报文体
    */
   private String message;
}

八、使用示例

    @Autowired
    private EndpointService endpointService;

    @PostMapping("/api/v1/endpoint/test/{appId}")
    public ResponseEntity<?> testEndpoint(@PathVariable String appId) {
        endpointService.doOnOpen(new RequestContent(appId, "test open method"));
        endpointService.doOnClose(new RequestContent(appId, "test close method"));
        return ResponseEntity.ok(DateUtil.now());
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,326评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,228评论 1 304
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,979评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,489评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,894评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,900评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,075评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,803评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,565评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,778评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,255评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,582评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,254评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,151评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,952评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,035评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,839评论 2 277

推荐阅读更多精彩内容