持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情
需求:
需要实现,在启动服务后,打开服务指定页面;
实现
考虑在服务启动类中,获取服务ip和端口,项目路径等信息;拼接指定网址页面;
代码:
以服务启动后,打开swagger接口页面;
打开浏览器,需要区分一下系统: 获取操作系统的名字
System.getProperty("os.name", "")
参考代码如下
private static void openBrowse(String url) throws Exception {
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Mac OS")) {
//苹果的打开方式
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
} else if (osName.startsWith("Windows")) {
//windows的打开方式。
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
} else {
// Unix or Linux的打开方式
String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
else
//这个值在上面已经成功的得到了一个进程。
Runtime.getRuntime().exec(new String[] { browser, url });
}
}
在启动类获取环境属性:只有使用
ConfigurableApplicationContext 和 Environment
ConfigurableApplicationContext 直接继承了 ApplicationContext, Lifecycle, Closeable 接口,所以 ConfigurableApplicationContext 是 ApplicationContext 的子类
Environment 这个接口代表应用运行时的环境。访问 property 的方法通过 Environment 继承的接口 PropertyResolver 暴露出去的。 数据来源有以下的几个方面
properties 文件 JVM 系统属性 系统环境变量 JNDI Servlet 上下文变量
Environment 在此基础上还提供了Profile特性,能够很好的对多环境支持。因此我们一般使用它来获取属性。 可以简单粗暴的把它理解为Profile 和 PropertyResolver 的组合
获取到指定属性后,使用String,format格式化字符串;
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext application = SpringApplication.run(N3AgentBooter.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.contextPath");
String url = String.format("http:%s:%s/%s/swagger-ui.html",ip,port,path);
openBrowse(url);
}
注意
获取path属性时,参数要根据时间情况来定; 如:
String path = env.getProperty("server.contextPath"); 或 String path = env.getProperty("server.servlet.context-path");