Springboot项目启动后自动打开访问
1、在Springboot项目中每次启动完项目,手动在浏览器输入访问地址太麻烦了。在启动类中加入下方代码,就可高效地在控制台中单击URL访问项目了~
示例代码:
@SpringBootApplication
@Slf4j
public class WebApplication {
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(WebApplication.class, args);
System.out.println("项目启动成功 *^_^* n" + " .-------. ____ __ n"
+ " | _ _ \ \ \ / / n" + " | ( ' ) | \ _. / ' n"
+ " |(_ o _) / _( )_ .' n" + " | (_,_).' __ ___(_ o _)' n"
+ " | |\ \ | || |(_,_)' n" + " | | \ `' /| `-' / n"
+ " | | \ / \ / n" + " ''-' `'-' `-..-' ");
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
if (StringUtils.isEmpty(path)) {
path = "";
}
log.info("n----------------------------------------------------------nt" +
"Application is running! Access URLs:nt" +
"Local访问网址: tthttp://localhost:" + port + path + "nt" +
"External访问网址: thttp://" + ip + ":" + port + path + "nt" +
"----------------------------------------------------------");
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
log.info("当前项目进程号:" + jvmName.split("@")[0]);
}
2、此外,还可以设置打开系统默认浏览器,并加载指定的页面。如下添加监听类。
示例代码:
package com.yc.star.web.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandRunner implements CommandLineRunner {
@Value("${spring.web.loginurl}")
private String loginUrl;
@Value("${spring.auto.openurl}")
private boolean isOpen;
@Override
public void run(String... args) {
if (isOpen) {
System.out.println("自动加载指定的页面");
try {
Runtime.getRuntime().exec("cmd /c start " + loginUrl); // 可以指定自己的路径
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("浏览器打开页面异常");
}
}
}
}
在”IT人才圈”微信公众号,发送”01″可获取更多相关源码教程或交流。
3、在application.yml文件中配置相关的参数:
spring:
auto:
openurl: true # 是否自动打开浏览器,false为否
web:
loginurl: http://localhost:8090 # 指定加载的页面地址
至此,可愉快地启动项目,等待浏览器自动加载我们指定的页面。