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



我有一个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 启动代码。

@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 包命令生成 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(( 将起作用。您需要修改代码,因为如果您尝试加载资源并使用org.springframework.core.io.Resource将其打包到jar中,则此行代码System.setProperty("webdriver.chrome.driver", resource.getFile().getPath());不起作用。

请参考:作为 jar 运行时找不到类路径资源。

尝试使用 ResourceLoader;

@Autowired
ResourceLoader resourceLoader;
...
Resource resource = resourceLoader.getResource("classpath:chromedriver.exe")
...

最新更新