search
HomeJavajavaTutorialHow to customize routing coverage in SpringBoot

    Background

    The company recently has a project in the second phase that requires the transformation of some functions, which involves the personalized customization of some of the built-in business interfaces of the framework and is compatible with the old interface functions. And add some new data returns. Since the front-end calls these interfaces are scattered and fragmented, and the modification and testing cost is high, we plan to provide routing coverage function at the framework level to speed up the project progress and reduce the system risks caused by modifications without technical content.

    Design

    • Provide custom annotations to specify the routing and new routing addresses that need to be covered

    • Scan all annotations when the system starts Data and mapping processing

    • Register custom route mapping configuration class

    Implementation

    Annotation definition

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    public @interface CoverRoute {
        String value() default "";
    }

    Annotation scanning and management

    Call the initRoute method when the system starts to map the original route and the corresponding overlay route to the map key-value pair

    public class ConverRouteUtil {
        private static HashMap<String, String> mappingRegist = new HashMap<>();
        public static void initRoute(Class runtimeClass, List<String> extraPackageNameList) {
            List<Class<?>> scanClassList = new ArrayList<>();
            if (!runtimeClass.getPackage().getName().equals(Application.class.getPackage().getName())) {
                scanClassList.addAll(ScanUtil.getAllClassByPackageName_Annotation(runtimeClass.getPackage(), CoverRoute.class));
            }
            for (String packageName : extraPackageNameList) {
                scanClassList.addAll(ScanUtil.getAllClassByPackageName_Annotation(packageName, CoverRoute.class));
            }
            for (Class clazz : scanClassList) {
                CoverRoute coverRoute = (CoverRoute) clazz.getAnnotation(CoverRoute.class);
                if (StringUtil.isEmpty(coverRoute.value())) {
                    continue;
                }
                RequestMapping requestMapping = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
                String classRoute = "";
                if (requestMapping != null) {
                    classRoute = requestMapping.value()[0];
                } else {
                    continue;
                }
                List<Method> methodList = Arrays.asList(clazz.getDeclaredMethods());
                for (Method method : methodList) {
                    PostMapping postMapping = method.getAnnotation(PostMapping.class);
                    String methodRoute = "";
                    if (postMapping != null) {
                        methodRoute = postMapping.value()[0];
                    } else {
                        GetMapping getMapping = method.getAnnotation(GetMapping.class);
                        if (getMapping != null) {
                            methodRoute = getMapping.value()[0];
                        }
                    }
                    if (!StringUtil.isEmpty(classRoute) && !StringUtil.isEmpty(methodRoute)) {
                        String orginalRoute = coverRoute.value() + methodRoute;
                        String redirectRoute = classRoute + methodRoute;
                        mappingRegist.put(orginalRoute, redirectRoute);
                    }
                }
            }
            if (mappingRegist.size() > 0) {
                System.out.println("扫描路由方法覆盖:" + mappingRegist.size() + "个");
            }
        }
        public static boolean checkExistCover(String orginalRoute) {
            return mappingRegist.containsKey(orginalRoute);
        }
        public static String getRedirectRoute(String orginalRoute) {
            return mappingRegist.get(orginalRoute);
        }
    }

    Customized RequestMappingHandlerMapping

    Inherit RequestMappingHandlerMapping and rewrite the lookupHandlerMethod method to overwrite it when spring performs routing

    public class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
        @Override
        protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
            if(ConverRouteUtil.checkExistCover(lookupPath)){
                String redirectRoute = ConverRouteUtil.getRedirectRoute(lookupPath);
                request.setAttribute("redirectTag","1");
                request.setAttribute("redirectRoute",redirectRoute);
                request.setAttribute("lookupPath",lookupPath);
                lookupPath = redirectRoute;
            }else{
                request.setAttribute("redirectTag","0");
            }
            return super.lookupHandlerMethod(lookupPath, request);
        }
        @Override
        protected RequestMappingInfo getMatchingMapping(RequestMappingInfo info, HttpServletRequest request) {
            String redirectTag = ConvertOp.convert2String(request.getAttribute("redirectTag"));
            if(redirectTag.equals("1")){
                String redirectRoute = ConvertOp.convert2String(request.getAttribute("redirectRoute"));
                boolean check = false;
                if( info.getPatternsCondition()!=null){
                    Set<String> set =  info.getPatternsCondition().getPatterns();
                    if(set.size()>0){
                        String[] array = new String[set.size()];
                        array = set.toArray(array);
                        String pattern = array[0];
                        if(pattern.equals(redirectRoute)){
                            check = true;
                        }
                    }
                }
                if(check){
                    return info;
                }else{
                    return super.getMatchingMapping(info, request);
                }
            }else{
                return super.getMatchingMapping(info, request);
            }
        }
    }

    Register RequestMappingHandlerMapping

    @Component
    public class WebRequestMappingConfig implements WebMvcRegistrations {
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            RequestMappingHandlerMapping handlerMapping = new CustomRequestMappingHandlerMapping();
            handlerMapping.setOrder(0);
            return handlerMapping;
        }
    }

    Usage example

    Add the @CoverRoute annotation to the personalized interface class , specify the routing address that needs to be covered, and create the same routing path. Access to the original interface address will be automatically forwarded to the project's personalized interface address

    Original interface

    @Controller
    @RequestMapping("/example/original")
    public class RedirectOriginalExampleController {
        @PostMapping("/getConfig")
        @ResponseBody
        @AnonymousAccess
        public Object getConfig(@RequestBody Map<String, Object> params) {
            Result result = Result.okResult();
            result.add("tag","original");
            return result;
        }
    }

    New interface

    @Controller
    @RequestMapping("/example/redirect")
    @CoverRoute("/example/original")
    public class RedirectExampleController {
        @PostMapping("/getConfig")
        @ResponseBody
        public Object getConfig(@RequestBody Map<String, Object> params) {
            Result result = Result.okResult();
            String param1 = ConvertOp.convert2String(params.get("param1"));
            result.add("tag","redirect");
            result.add("param1",param1);
            return result;
        }
    }

    The above is the detailed content of How to customize routing coverage in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

    JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

    Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

    JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

    TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

    JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

    JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

    Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

    Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

    Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

    What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

    Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

    Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

    The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software