SpringBoot loaded automatically routing prefix

@RequestMapping () need to be added when the controller routing address registered to the vessel, if the deeper layers of the project, the address will be very long, and there are many different prefixes, each writing a controller must repeat very troublesome, since Spring so powerful, there is no mechanism to automatically generate a route prefix?

Thinking: How can @RequestMapping without URL prefix ------> so that we can automatically add the prefix configuration class

Now with @RequestMapping () can be registered route, it must have a corresponding configuration class can modify the routing address.

RequestMappingHandlerMapping came into being. We need to write a configuration class inherited RequestMappingHandlerMapping and rewrite them getMappingForMethod method.

public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {
    //missyou.api-package = com.chauncy.missyou.api  写在application.properties中
    @Value("${missyou.api-package}")
    private String apiPackagePath;
    
    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        //我们所需的路由信息在handlerType中
        RequestMappingInfo mappingForMethod = super.getMappingForMethod(method, handlerType);
        if (mappingForMethod != null) {
            String prefix = this.getPrefix(handlerType);
            //这里prefix = "/v1"但远远不够还要加上路由的自己设的地址
            return RequestMappingInfo.paths(prefix).build().combine(mappingForMethod);
        }
        return null;
    }

    private String getPrefix(Class<?> handlerType) {
        String packName = handlerType.getPackage().getName();
        //为什么这么处理?因为我们只需要和入口文件同级的包名,packName为该路由的完整包名
        //packname = com.chauncy.missyou.api.v1 而我们只需要v1这个前缀,
        String newPackName = packName.replaceAll(this.apiPackagePath, "");
        return newPackName.replace(".", "/");
    }
}

Note: You can not simply put the configuration class is loaded directly into the container with Component Notes

Interface is needed to form loaded into the container

@Component
public class AutoPrefixUrlMappingConfiguration implements WebMvcRegistrations {
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new AutoPrefixUrlMapping();
    }
}

why? Because it's time to design the class specified

protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
            return this.webFluxRegistrations != null && this.webFluxRegistrations.getRequestMappingHandlerMapping() != null ? this.webFluxRegistrations.getRequestMappingHandlerMapping() : super.createRequestMappingHandlerMapping();
        }

If getRequestMappingHandlerMapping () Returns the value is null, it is not a new subsequent processing.

Guess you like

Origin www.cnblogs.com/chauncyL/p/12497225.html