Spring Boot JAR应用程序未从资源文件夹读取chromedriver.exe

问题描述 投票:0回答:2

我有一个Spring Boot项目,该项目正在使用硒对不同应用程序进行自动化测试。项目的输出档案是一个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
java spring spring-boot selenium
2个回答
0
投票

尝试使用ResourceLoader;

@Autowired
ResourceLoader resourceLoader;

...
Resource resource = resourceLoader.getResource("classpath:chromedriver.exe")
...

0
投票

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

参考此:Classpath resource not found when running as jar

© www.soinside.com 2019 - 2024. All rights reserved.