import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 开发测试工具
*/
@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;
/**
* 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("/**");
}
private String getTestUrl() {
String testUrl = "http://localhost";
testUrl += ":" + port;
if (!"".equals(contextPath)) {
testUrl += "/" + contextPath;
}
testUrl += "/test";
return testUrl;
}
/**
* 使用浏览器打开测试url
*/
public void openTestUrl() {
String url = this.getTestUrl();
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等调试使用。