SpringBoot启动执行代码
废话少说上代码
@Component
@Slf4j
public class LimsCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
printInfo();
//openBrowser();
}
private void openBrowser(){
try {
if (ProfileUtils.getActiveProfile().equals(ProfileUtils.DEV)){
Runtime.getRuntime().exec("cmd /c start http://localhost:9999/doc.html");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void printInfo(){
ApplicationContext context = SpringContextHolder.getContext();
Environment env = context.getEnvironment();
String[] profiles = env.getActiveProfiles();
log.info("当前运行环境:{}", profiles[0]);
String ip = "";
try{
ip = InetAddress.getLocalHost().getHostAddress();
}catch (Exception e){
log.error(e.getMessage());
}
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path","");
log.info("本地Swagger文档:http://localhost:{}{}/doc.html",port,path);
log.info("内网Swagger文档:http://{}:{}{}/doc.html",ip,port,path);
}
}
我这里使用的是CommandLineRunner接口,实现CommandLineRunner接口需要重写run()方法。我在我代码里实现了项目启动后打印出Swagger地址。
如果有多个方法需要执行可以通过增加注解 @Order(value=?) 来指定执行顺序,从而帮助我们更好的书写代码。