SpringBoot应用中在启动的时候让应用在启动的时候,在windows系统中的启动目录下创建快捷方式,在系统启动的时候启动指定应用。这里使用jshortcut来实现。
jshortcut的github地址:https://github.com/jimmc/jshortcut,
可以下载下来自己打jar包,然后用VS编译一下src/jni/ 目录下的compile文件编译jshortcut.cpp文件,编译前想修改bat其中的jdk目录,compile.bat编译成32位的,compile-oberzalek.bat是编译成64位的,编译成jshortcut.dll文件。
import net.jimmc.jshortcut.JShellLink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.File;
/**
* 程序第一次启动的时候再系统的启动目录下创建应用的快捷方式,让程序随系统开机自启
* 目前请让 jsshortcut.dll文件和应用程序在同级目录
*/
@Component
public class LinkFileStartUp implements ApplicationRunner{
private static Logger logger = LoggerFactory.getLogger(Logger.class);
@Override
public void run(ApplicationArguments args) throws Exception {
/* 获取系统的自启目录 */
String startFolder = "";
String osName = System.getProperty("os.name");
String userHome = System.getProperty("user.home");
if (osName.equals("Windows 7") || osName.equals("Windows 8") || osName.equals("Windows 10")
|| osName.equals("Windows Server 2012 R2") || osName.equals("Windows Server 2014 R2")
|| osName.equals("Windows Server 2016")) {
startFolder = userHome
+ "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
}
String savePath = startFolder;
String appName = "test.exe";
String relativelyPath=System.getProperty("user.dir");
// 设置 jshortcut.dll 文件的路径,设置为与当前应用同级目录
System.setProperty("JSHORTCUT_HOME",relativelyPath);
String exePath = relativelyPath+File.separator+"test.exe";
logger.info("系统自启目录:{}",startFolder);
logger.info("exe文件路径:{}",exePath);
File file = new File(savePath+appName);
if (!file.exists()){//如果快捷方式不存在就创建指定的快捷方式
/* 创建快捷方式到系统启动目录 */
boolean linkFileRet = createLinkFile(savePath, appName, exePath);
logger.info("快捷方式创建结果:{}",linkFileRet);
}
}
/**
* 为指定文件创建快捷方式到指定目录下,指定文件名称为英文名称,中文会导致执行无效
* @param savePath
* @param lnkName
* @param exePath
* @return
*/
public static boolean createLinkFile(String savePath, String lnkName, String exePath){
File exeFile = new File(exePath);
File saveDir = new File(savePath);
if (!exeFile.exists() || !saveDir.exists()){
System.out.println("路径或者文件为空。");
return false;
}
try {
JShellLink link = new JShellLink();
link.setName(lnkName);//快捷方式的名称
link.setFolder(savePath);//存放路径
link.setPath(exePath);//指向的exe
link.save();
}catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
}
dll文件与本程序打的exe文件在同一级目录,把jar包添加到项目的依赖,可以创建lib目录放进去,然后需要在项目中的pom文件中添加坐标依赖:
<!--快捷方式 依赖jar--> <dependency> <groupId>jshortcut</groupId> <artifactId>jshortcut</artifactId> <version>0.4</version> <scope>system</scope> <systemPath>${project.basedir}/lib/jshortcut.jar</systemPath> </dependency>
版本那行不能少,要不然项目启动会报错。
将项目打成jar包这时候会把jshortcut..jar打包进项目中,再将项目用exe4j打成exe程序在windows环境下运行,jshort.dll文件放在和exe文件同级目录下。
附上文件链接:
jshortcut.jar和jshortcut.dll
https://pan.baidu.com/s/1DpzeYVIZfC6ld0Qk2HP2SA 密码:io0b