2017-08-08 25 views
0

我打算做一個@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> 
+0

通過哪種魔法,您希望主方法自動裝入任何東西而不加載任何彈簧環境呢?您目前正在使用主要方法。這個主要方法訪問一個變量'driver',它是null,因爲你從來沒有設置它。由於你實際上並沒有啓動Spring,因此絕對沒有什麼事情會對你的'@ Autowired'做些什麼。您需要首先初始化Spring,具體取決於您使用的是哪個Spring,或者您想要使用哪種Spring。 –

+0

我從你的評論中得到了一些提示,但是你能寫一個答案嗎? – Salman

+0

由於您不告訴我們您是否使用了spring boot,除了「start spring」之外,很難回答任何問題,這取決於您使用的彈簧。 –

回答

0

使用Spring,你必須以某種春季開始,這意味着初始化它創建你的豆子,彈簧等方面

在春季啓動的背景下,這意味着,你有你這樣的主要方法...

public static void main(String[] args) { 
    SpringApplication.run(MyApplication.class, args); 
} 

...與MyApplication是與@SpringBootApplication註釋的類(通常,這是它包含的主要方法,同一個類)。這將啓動一個spring引導上下文。

由於主要方法是靜態的,無法訪問非靜態成員,並且afaik spring不會連接靜態變量,所以您需要以某種其他方式訪問它,例如在一個bean中,例如在@PostConstruct方法中,或者你從上面的方法得到的ApplicationContext ...

ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class, args); 
    WebDriverService service = context.getBean(WebDriverService.class); 
+0

我從你的答案中學到了很多東西。謝謝。 – Salman

+1

對於開始,我建議使用https://start.spring.io/中的Spring Initializr,它爲您創建一個基本項目,您可以繼續。使它更容易啓動。 –

0
@SpringBootApplication  
public class SeleniumApplication implements CommandLineRunner { 

     @Autowired 
     WebDriverService driver; 

     public static void main(String[] args) { 
      SpringApplication.run(SeleniumApplication .class, args); 
     } 

     @Override 
     public void run(String... strings) throws Exception { 
      driver.webDriverGetter().get("https://www.google.com/");  
     } 

    } 

實際上你需要爲了實現commandLineRunner要使用自動連接豆 你不能做到這一點的主要方法中BTW主類實際上應該有這個@SpringBootApplication注意。

相關問題