SpringBoot获取自定义注解

·  阅读 341

通过Spring ApplicationContext以及AnnotationUtil获取自定义注解

 Set<String> pathSet = new HashSet<>();

ApplicationContext context = ApplicationContextProvider.getContext();
//通过注解获取bean
Map<String, Object> map = context.getBeansWithAnnotation(RestController.class);

 for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (AnnotationUtils.findAnnotation(entry.getValue().getClass(), RpcController.class) != null) {
                continue;
            }

            Method[] methods = entry.getValue().getClass().getMethods();
            RequestMapping reqMap = AnnotationUtils.findAnnotation(entry.getValue().getClass(), RequestMapping.class);
            if (Objects.isNull(reqMap)) {
                continue;
            }

            String baseUrl = reqMap.value()[0];

            String methodPath = null;
            for (Method method : methods) {
                if (Objects.nonNull(AnnotationUtils.findAnnotation(method, ProxyAuth.class)) || Objects.nonNull(AnnotationUtils.findAnnotation(method, ApiAuth.class))) {
                    if (Objects.nonNull(AnnotationUtils.findAnnotation(method, PostMapping.class))) {
                        methodPath = AnnotationUtils.findAnnotation(method, PostMapping.class).value()[0];
                    } else if (Objects.nonNull(AnnotationUtils.findAnnotation(method, GetMapping.class))) {
                        methodPath = AnnotationUtils.findAnnotation(method, GetMapping.class).value()[0];
                    } else if (Objects.nonNull(AnnotationUtils.findAnnotation(method, RequestMapping.class))) {
                        if (StringUtils.isNotBlank(AnnotationUtils.findAnnotation(method, RequestMapping.class).value()[0])) {
                            methodPath = AnnotationUtils.findAnnotation(method, RequestMapping.class).value()[0];
                        }
                    }
                }
                if (StringUtils.isNotBlank(methodPath)) {
                    pathSet.add(String.format("/gateway%s%s", baseUrl, methodPath));
                }
            }
        }

        pathSet.forEach(System.out::println);

复制代码
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改