/**
* 开发测试工具
*/
@RestController
@RequestMapping("/")
public class TestController implements ApplicationListener<ApplicationReadyEvent>, WebMvcConfigurer {
@GetMapping("/test")
public String test() {
//do something
return "test";
}
/**
* 应用端口port及contextPath
*/
@Value("${server.port:8080}")
private String port;
@Value("${server.servlet.context-path:}")
private String contextPath;
/**
* 测试url
*/
private static final String TEST_URL = "http://localhost:%s/%s/test";
/**
* ApplicationReadyEvent事件(系统启动后)
*
* @param event
*/
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
this.openTestUrl();
//do something
}
/**
* 拦截器
*
* @param registry
*/
@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("/**");
}
/**
* 使用浏览器打开测试url
*/
public void openTestUrl() {
String url = String.format(TEST_URL, port, contextPath);
System.out.println("使用浏览器打开" + url);
//使用默认浏览器打开url命令
try {
String osName = System.getProperties().getProperty("os.name");
if (osName.toLowerCase().startsWith("windows")) {
Runtime.getRuntime().exec(String.format("explorer %s", url));
} else if (osName.toLowerCase().startsWith("mac os")) {
String[] cmd = {"/bin/sh", "-c", String.format("/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome %s", url)};
Runtime.getRuntime().exec(cmd);
}
System.out.println("使用浏览器打开完成");
} catch (IOException e) {
System.out.println("使用浏览器打开失败");
e.printStackTrace();
}
}
}
作用:
1、增加一个测试接口:/test
2、监听ContextRefreshedEvent事件,当应用启动之后,读取应用端口port及contextPath配置,并调用本地默认浏览器打开测试地址。解决多应用同时开发且端口不一、contextPath过长需要来回复制问题;以及应用启动时间过慢,不知何时启动完成问题(浏览器打开即启动完成)。
3、预留HandlerInterceptor方法,方便填写一些诸如登陆信息等操作,便于一些从ThreadLocal中读取信息的工具类如LoginUtil等调试使用。