我打算做一個@Service
,它給了我一個具有依賴注入的Selenium WebDriver。下面是代碼:在Main類中使用@Autowiered的NullPointerException
import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Service;
@Service
public class WebDriverService {
public WebDriver webDriverGetter(){
File file = new File(SeleniumApplication.class.getClassLoader().getResource("driver/chromedriver.exe").getFile());
String driverPath=file.getAbsolutePath();
System.out.println("Webdriver is in path: "+driverPath);
System.setProperty("webdriver.chrome.driver",driverPath);
WebDriver driver= new ChromeDriver();
return driver;
}
}
,然後調用服務的主類象下面這樣:
public class SeleniumApplication {
@Autowired
static WebDriverService driver;
public static void main(String[] args) {
driver.webDriverGetter().get("https://www.google.com/");
}
}
但它與抱怨:
Exception in thread "main" java.lang.NullPointerException
我已在c hromeDriver.exe
路徑
src\main\resources\driver\chromedriver.exe
在pom.xml
我有
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
通過哪種魔法,您希望主方法自動裝入任何東西而不加載任何彈簧環境呢?您目前正在使用主要方法。這個主要方法訪問一個變量'driver',它是null,因爲你從來沒有設置它。由於你實際上並沒有啓動Spring,因此絕對沒有什麼事情會對你的'@ Autowired'做些什麼。您需要首先初始化Spring,具體取決於您使用的是哪個Spring,或者您想要使用哪種Spring。 –
我從你的評論中得到了一些提示,但是你能寫一個答案嗎? – Salman
由於您不告訴我們您是否使用了spring boot,除了「start spring」之外,很難回答任何問題,這取決於您使用的彈簧。 –