2016-02-04 103 views
1

我正在努力與黃瓜和春季配置。 我正在使用頁面對象模式和BrowserFactory編寫硒框架。黃瓜春季和班級配置

當我使用@ComponentScan,@Component和@Autowire註釋一切正常,但是當我想在@Configuration類中使用@Bean註釋(BrowserFactory註冊少量瀏覽器驅動程序)創建更復雜的bean時,它不會工作,在調試過程中,我正在嘗試使用Autowire的每個變量的空值。

我使用的是Spring 4.2.4,版本1.2.4中的所有黃瓜依賴項。

配置:

@Configuration 
public class AppConfig { 

@Bean 
@Scope("cucumber-glue") 
public BrowserFactory browserFactory() { 
    BrowserFactory browserFactory = new BrowserFactory(); 
    browserFactory.registerBrowser(new ChromeBrowser()); 
    browserFactory.registerBrowser(new FirefoxBrowser()); 
    return browserFactory; 
} 

@Bean(name = "loginPage") 
@Scope("cucumber-glue") 
public LoginPage loginPage() throws Exception { 
    return new LoginPage(); 
} 

@Bean(name = "login") 
@Scope("cucumber-glue") 
public Login login() { 
    return new Login(); 
} 
} 

POP:

public class LoginPage extends Page { 

    public LoginPage() throws Exception { 
    super(); 
    } 
    ... 
} 

頁:

public class Page { 

    @Autowired 
    private BrowserFactory browserFactory; 

    public Page() throws Exception{ 
    ... 
    } 
} 

登錄:

public class Login { 

    @Autowired 
    private LoginPage loginPage; 

    public Login(){} 
    ... 
} 

個步驟:

@ContextConfiguration(classes = {AppConfig.class}) 
public class LoginSteps { 

    @Autowired 
    Login login; 

    public LoginSteps(){ 
    } 

    @Given("^an? (admin|user) logs in$") 
    public void adminLogsIn(Login.User user) throws Exception { 
    World.currentScenario().write("Logging in as " + user + "\n"); 
    login.as(user); 
    } 
} 

錯誤:

cucumber.runtime.CucumberException: Error creating bean with name 'LoginSteps': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: Login LoginSteps.login; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'login': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private LoginPage Login.loginPage; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginPage' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [LoginPage]: Factory method 'loginPage' threw exception; nested exception is java.lang.NullPointerException

現在最有趣的部分... BrowserFactory在世界級的是正確的自動裝配Autowired!

世界:

public class World { 

    @Autowired 
    private BrowserFactory browserFactory; 
    ... 
} 

回答

0

所以,我會回答我的問題:)

問題是,我打電話BrowserFactory頁面構造內。 看起來這個bean尚未創建並導致NPE。

爲了解決這個I:

  • 添加@Lazy批註配置(即使用此配置的所有元素,無論是在該類中定義和那些將被掃描發現將作爲懶惰被創建)
  • 到瀏覽器工廠遷至調用@PostConstruct方法

兩件事來增加Spring配置的可讀性:

  • 添加@ComponentScan到配置
  • 類與沒有構造參數使用了@Component註解和@Scope(「黃瓜膠」)註釋所以bean創建可以從AppConfig.class
除去