2015-11-11 36 views
0

我得到了沒有符合條件的bean類型的[com.vaadin.ui.Horizo​​ntalLayout]找到依賴性錯誤,當我嘗試從另一個配置文件注入參數時,如下所示: Main Config:找不到符合條件的類型的bean,vaadin

@Configuration 
@EnableVaadin 
@Import(NavigationBar.class) 
@ComponentScan("net.elenx") 
public class SpringConfig { 

    //Create whole view of MainView 
    @Bean 
    VerticalLayout template(@Qualifier("navigationBar") HorizontalLayout navigationBar) { 
     VerticalLayout template = new VerticalLayout(); 
     //NavigationBar navigationBar = new NavigationBar(); 
     Sidebar sidebar = new Sidebar(); 
     template.setMargin(false); 
     template.setSpacing(false); 
     template.setHeight("100%"); 
     template.addComponent(navigationBar); 
     template.addComponent(sidebar.getSidebar()); 
     template.setExpandRatio(sidebar.getSidebar(), 1.0f); 
     return template; 
    } 
} 

二配置:

@Configuration 
@EnableVaadin 
public class NavigationBar { 

    @Bean 
    HorizontalLayout navigationBar(Button hamburgerButton, Label elenxLogo) { 
     System.out.println("Hello from NavigationBar bean!"); 
     HorizontalLayout navbar = new HorizontalLayout(); 
     navbar.setWidth("100%"); 
     navbar.setMargin(true); 
     navbar.setHeight(50, Sizeable.Unit.PIXELS); 
     navbar.addComponent(hamburgerButton); 
     navbar.addComponent(elenxLogo); 
     navbar.addStyleName("navigation-bar"); 
     return navbar; 
    } 

    @Bean 
    Button hamburgerButton() { 
     Button hamburgerButton = new Button(); 
     hamburgerButton.addStyleName("hamburger-button"); 
     hamburgerButton.setIcon(VaadinIcons.MENU); 
     return hamburgerButton; 
    } 

    @Bean 
    Label elenxLogo() { 
     Label logo = new Label("ElenX"); 
     logo.addStyleName("elenx-logo"); 
     logo.setWidthUndefined(); 
     logo.setEnabled(false); 
     return logo; 
    } 
} 

那麼什麼是實現這一注射corrent方式?我想爲每個元素都有Beans,只是注入它們來構建整個佈局。當我試圖改變這一行:

@Bean 
VerticalLayout template(HorizontalLayout navigationBar) { 

要這樣:

@Bean 
VerticalLayout template(@Qualifier("navigationBar") HorizontalLayout navigationBar) { 

我得到「無法自動裝配‘組件’類型的預選賽豆必須的。」的錯誤。我是新鮮的春天,我不知道我做錯了什麼,不應該Spring我的Horizo​​ntalLayout navigationBar方法與VerticalLayout模板(Horizo​​ntalLayout navigationBar)參數匹配?

回答

1

你得到的錯誤消息告訴您的是,預選賽豆(這是@Qualifier("navigationBar")註釋的HorizontalLayout)需要一個Spring @Component,那就是需要HorizontalLayout@Component進行註釋這顯然是不可能的。

您的方法存在的另一個問題是Spring bean默認爲單例。因此,您最終只能在應用程序中使用navigationBar佈局的一個實例。這當然是不夠的,因爲您需要爲每個爲用戶創建的新UI對象創建一個新實例。 navigationBar Spring bean需要有prototype scope,以便每個注入事件的應用程序上下文創建一個新實例。

此外,我強烈建議您不要使用單獨的Vaadin UI組件進行自動裝配。 Spring依賴注入機制並不意味着在這個級別上使用。您應該使用更多粗粒度組件作爲Spring bean,例如整個Vaadin views或後端服務。構建單獨的UI組件(如導航欄,表單或視圖)應該在不依賴注入的情況下完成。使用DI過度殺毒是因爲您可以通過簡單地調用它們的構造函數來爲通用UI組件創建實例,例如導航欄,漢堡按鈕或elenx徽標。在這種情況下,不需要在UI組件中自動裝配,這使得Spring容器的使用完全是冗餘的。

編輯:模塊化上的分量的水平Vaadin碼的最好的方法是使用CustomComponent類作爲新組件的基類。您將構建一個名爲NavigationBar的新CustomComponent子類,然後您可以實例化並將其添加到像任何其他Vaadin組件一樣的佈局中。

+0

好的我明白了,那麼在Vaadin編寫UI模塊(如邊欄,導航欄)的最佳方式是什麼?我關心最好的代碼,謝謝你的回答! – Zeezl

+0

不客氣,我相應地編輯了我的答案。 –

相關問題