首页 > 解决方案 > 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

标签: javaspringspring-bootselenium

解决方案


resource.getFile() 期望资源本身在文件系统上可用,即它不能嵌套在 jar 文件中。在这种情况下,resource.getInputStream() 将起作用。您需要修改您的代码,因为System.setProperty("webdriver.chrome.driver", resource.getFile().getPath());如果您尝试加载资源并使用 org.springframework.core.io.Resource 将其打包到 jar 中,这行代码将不起作用。

请参阅:作为 jar 运行时找不到 Classpath 资源


推荐阅读