SpringBoot开发调试工具类DevTool

/**
 * 开发调试工具
 */
@RestController
@RequestMapping("/dev")
public class DevTool implements ApplicationListener<ContextRefreshedEvent>, WebMvcConfigurer {

    /**
     * 应用端口port及contextPath
     */
    @Value("${server.port}")
    private String port;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * 测试url
     */
    private static final String TEST_URL = "http://localhost:%s/%s/dev/test";

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    /**
     * 使用浏览器打开测试url
     */
    public void openTestUrl() {
        String url = String.format(TEST_URL, port, contextPath);
        System.out.println("使用浏览器打开" + url);
        //使用chrome浏览器打开url命令
        String[] cmd = {"/bin/sh", "-c", String.format("/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome %s", url)};
        try {
            Runtime.getRuntime().exec(cmd);
            System.out.println("使用浏览器打开完成");
        } catch (IOException e) {
            System.out.println("使用浏览器打开失败");
            e.printStackTrace();
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        this.openTestUrl();
        //do something
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                //do something
                return true;
            }
        }).addPathPatterns("/**");
    }

}

作用:
1、增加一个测试接口:/dev/test
2、监听ContextRefreshedEvent事件,当应用启动之后,读取应用端口port及contextPath配置,并调用本地chrome打开测试地址。解决多应用同时开发且端口不一、contextPath过长需要来回复制问题;以及应用启动时间过慢,不知何时启动完成问题(浏览器打开即启动完成)。
3、预留HandlerInterceptor方法,方便填写一些诸如登陆信息等操作,便于一些从ThreadLocal中读取信息的工具类如LoginUtil等调试使用。


觉得内容还不错?打赏个钢镚鼓励鼓励!!👍