自定义注解实现路由到哪个请求

Posted mashiso

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义注解实现路由到哪个请求相关的知识,希望对你有一定的参考价值。

一、自定义注解 PreRoute 

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Lazy(false)
public @interface PreRoute {
    public RequestUrl requestWay();
}

@Target(ElementType.TYPE):作用于类上

@Retention(RetentionPolicy.RUNTIME):运行时期

@Component:标注为spring组件

@Lazy:懒加载

 

二、自定义实现BeanPostProcessor

#postProcessAfterInitialization():bean初始化方法调用后被调用

@Component
public class RouteBeanPostProcessor implements BeanPostProcessor{

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
     //如果是preRoute标注的注解,则注册到PreRouteEngine中
if (bean.getClass().isAnnotationPresent(PreRoute.class) && (bean instanceof PreRouteRule)) { Class beanClass = bean.getClass(); PreRoute preRoute = (PreRoute) beanClass.getAnnotation(PreRoute.class); PreRouteEngine.registry(preRoute.requestWay(), (PreRouteRule) bean); } return bean; } }

 

public class PreRouteEngine {
    private static final Map<RequestUrl, PreRouteRule> RULE_RESP = new ConcurrentHashMap<>();
    
    public static void registry(RequestUrl requestUrl, PreRouteRule preRouteRule) {
        RULE_RESP.put(requestUrl, preRouteRule);

    }

    public static void invoke(ChannelRequest channelRequest) {
        RequestUrl requestUrl = channelRequest.getRequestUrl();
        PreRouteRule preRouteRule = RULE_RESP.get(requestUrl);
        if(preRouteRule!=null){
            preRouteRule.preRoute(channelRequest.getPublicRequest());
        }
    }
}
public interface PreRouteRule {
    //逻辑具体的处理
    public void preRoute(PublicRequest publicRequest);
}

 

三、自己实现PreRouteRule接口

类上标注 @PreRoute(requestWay=RequestUrl.MCP_UNREAD_COUNT),表明是自定义注解的类。

requestWay:添加到map中的key,value值为接口的实现类 PreRouteRule。

@PreRoute(requestWay=RequestUrl.MCP_UNREAD_COUNT)
public class McpUnreadCountPreRoute implements PreRouteRule{

    @Override
    public void preRoute(PublicRequest publicRequest) {
        publicRequest.setDeviceOs(JGWConstant.DEFAULT_DEVICEOS);
        if(StringUtils.isNotBlank(publicRequest.getDeviceInfo())){
            Map<String, String> deviceInfoMap = (Map<String, String>) JSON.parse(publicRequest.getDeviceInfo());
            if(StringUtils.isNotBlank(deviceInfoMap.get("deviceOs"))){
                publicRequest.setDeviceOs(deviceInfoMap.get("deviceOs"));
            }
        }
        
    }

}

 





以上是关于自定义注解实现路由到哪个请求的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段11——vue路由的配置

VSCode自定义代码片段11——vue路由的配置

从零开始学springboot-6.手写拦截器和自定义注解

Android 组件化路由组件 ( 页面跳转参数依赖注入 )

Kotlin 元编程之 KSP 实战:通过自定义注解配置Compose导航路由

Kotlin 元编程之 KSP 实战:通过自定义注解配置Compose导航路由