springboot动态设置@RequestMapping的url请求路径

31人浏览 / 0人评论

springboot动态设置@RequestMapping的url请求路径(从配置文件中获取或默认)

controller层

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @GetMapping
    public String get(){
        return "get";
    }
    @PostMapping
    public String set(String name){
        return name;
    }
}

配置类1

import com.example.demo.controller.TestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;

public class JiaRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    private String getUrl="url/get";//默认的请求url
    private String setUrl="url/set";//默认的请求url

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
    }
    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) {
        RequestMappingInfo info = super.getMappingForMethod(method, handlerType);
        if(handlerType== TestController.class){
            if(method.getName().equals("get")){
                return RequestMappingInfo.paths(getUrl).build().combine(info);
            }else if(method.getName().equals("set")){
                return RequestMappingInfo.paths(setUrl).build().combine(info);
            }
        }
        return info;
    }
}

配置类2

import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class JiaWebMvcConfiguration implements WebMvcRegistrations {
    public JiaWebMvcConfiguration(){
        System.out.println("VersionControlWebMvcConfiguration");
    }
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping(){
        return new JiaRequestMappingHandlerMapping();
    }
}

private String getUrl="url/get";//get方法默认的请求url

private String setUrl="url/set";//set方法默认的请求url

如果原来的**Mapping中已经有路径,那么请求路径就是 **Mapping中的路径+getUrl的路径

默认请求路径可以从配置文件中获取

全部评论