java - Spring Boot JAR 应用程序未从资源文件夹中读取 chromedriver.exe
问题描述
我有一个 Spring Boot 项目,它使用 selenium 对不同的应用程序进行自动化测试。项目的输出存档是一个 JAR 文件。我有下面的代码来启动 chrome 浏览器。
static {
try {
Resource resource = null;
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains(IAutomationConstans.WINDOWS_OS_NAME)) {
resource = new ClassPathResource("chromedriver.exe");
} else if (osName.contains(IAutomationConstans.LINUX_OS_NAME)) {
resource = new ClassPathResource("chromedriver");
}
System.setProperty("webdriver.chrome.driver", resource.getFile().getPath());
ChromeOptions capabilities = new ChromeOptions();
webdriver = new ChromeDriver(capabilities);
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
} catch (Exception e) {
System.out.println("Not able to load Chrome web browser "+e.getMessage());
}
}
除了这个之外,我还有下面的执行自动化代码的 Spring Boot 代码。
@SpringBootApplication
@ComponentScan("com.test.automation")
@PropertySource(ignoreResourceNotFound = false, value = "classpath:application.properties")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class TestAutomation{
public static void main(String[] args) {
System.out.println("&&&&&&&&&&&&&&&&&&&&&");
SpringApplication.run(TestAutomation.class, args);
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%");
}
}
我已将 chromedriver.exe 放在 src\main\resources 下。如果我通过右键单击从 Eclipse 执行 TestAutomation 类,则一切正常。
但是,如果我通过 mvn package 命令生成 jar 文件并执行 JAR 文件,则会出现以下错误。
Not able to load Chrome web browser class path resource [chromedriver.exe] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/user/automation/target/automationapp-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/chromedriver.exe
解决方案
resource.getFile() 期望资源本身在文件系统上可用,即它不能嵌套在 jar 文件中。在这种情况下,resource.getInputStream() 将起作用。您需要修改您的代码,因为System.setProperty("webdriver.chrome.driver", resource.getFile().getPath());
如果您尝试加载资源并使用 org.springframework.core.io.Resource 将其打包到 jar 中,这行代码将不起作用。
推荐阅读
- caching - 在 Snowflake 虚拟仓库的工作节点中如何处理缓存一致性?
- mysql - 使用 mysql 命令从一个 docker 容器到另一个
- django - 将密钥添加到 Django i18n 加载的标签
- javascript - 为什么我的 if、else if 和 else 语句不能正常工作?
- javascript - Microsoft Graph API:在 Outlook 桌面上调用 getAccessToken 时出现错误 13012
- ruby-on-rails - 迁移 Rails 6.0.34 -> 6.1 后,我无法在 config/environments/development.rb 中使用模型
- java - 在 Java 中使用 CA 证书连接到 Vault
- angular - 如何以角度在页面上创建多个传单地图
- unicode - 有没有办法强制以我的字体将 RTL 字符写为 LTR
- azure - Azure webapp 部署