0%

springboot动态新增restful接口

说明

springboot动态增加和删除restful接口.

代码

@Service
public class Test {
    @Autowired
    RequestMappingHandlerMapping requestMappingHandlerMapping;

    // 初始化后自动添加一个 GET /test 接口
    @PostConstruct
    public void test() throws NoSuchMethodException {
        RequestMappingInfo.BuilderConfiguration options = new RequestMappingInfo.BuilderConfiguration();
        options.setPatternParser(new PathPatternParser());
        RequestMappingInfo requestMappingInfo = RequestMappingInfo
                .paths("/test")
                .produces("application/json;charset=UTF-8")
//                .consumes("text/plain;charset=UTF-8")
                .methods(RequestMethod.GET)
                .options(options)
                .build();
        requestMappingHandlerMapping.registerMapping(requestMappingInfo, "handler", Handle.class.getDeclaredMethod("test", HttpServletRequest.class));
        // 删除接口
        //requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);
    }
}

@RestController
public class Handler {
    public String test(HttpServletRequest request)  {
        return "hello";
    }
}