2016-02-29 87 views
1

我有一個vaadin項目,我需要使用@Autowired Spring註釋。所以,我用的是vaadin彈簧附加Vaadin-spring autowired

<dependency> 
    <groupId>com.vaadin</groupId> 
    <artifactId>vaadin-spring</artifactId> 
    <version>1.0.0</version> 
</dependency> 

現在,如果我在UI類定義自動裝配Autowired類,它工作正常。但是如果我在另一個類中定義了自動裝配類,那麼這個類總是空的。例如在這種情況下,「serv」始終爲空。

@SuppressWarnings("serial") 
public class ProfileWindow extends Window { 

    @Autowired 
    private Servizio serv; 

    ... 
    ... 

    private Component buildFooter() { 
     HorizontalLayout footer = new HorizontalLayout(); 
     footer.addStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR); 
     footer.setWidth(100.0f, Unit.PERCENTAGE); 

     Button ok = new Button("OK"); 
     ok.addStyleName(ValoTheme.BUTTON_PRIMARY); 
     ok.addClickListener(new ClickListener() { 
      @Override 
      public void buttonClick(ClickEvent event) { 
       Dati dd = new Dati(Double.parseDouble(nomeField.getValue()), Double.parseDouble(cognomeField.getValue())); 

       String out = serv.converti(dd); 

       Notification success = new Notification(out); 
       success.setDelayMsec(2000); 
       success.setStyleName("bar success small"); 
       success.setPosition(Position.BOTTOM_CENTER); 
       success.show(Page.getCurrent()); 

       BsciEventBus.post(new ProfileUpdatedEvent()); 
       close(); 


      } 
     }); 
     ok.focus(); 
     footer.addComponent(annulla); 
     footer.setComponentAlignment(annulla, Alignment.TOP_LEFT); 
     footer.addComponent(ok); 
     footer.setComponentAlignment(ok, Alignment.TOP_RIGHT); 

     return footer; 
    } 
} 

ServizioImpl.java

@SpringComponent 
public class ServizioImpl implements Servizio { 

    @Override 
    public String converti(Dati dati) { 

     //implementation... 
     return "out"; 
    } 

} 

你能幫我使用自動裝配Autowired annotataion?

你有一些示例代碼來提示嗎?我不明白如何解決這個問題。 如果我在ProfileWindow上使用@SpringComponent,則自動佈線註解不起作用。

感謝

+0

Spring可以自動裝配只有在它創建的對象領域的問題。它無法知道你手動創建了一個新的實例。因此,'ProfileWindow'必須也是一個Spring組件,你必須從Spring上下文中獲取它的實例,以便它的字段可以被其他組件的實例自動裝配。 – Morfic

+0

對不起,但如果我在'ProfileWindows'上使用@SpringComponent,那麼自動裝配不起作用。有沒有辦法在某個地方定義Servizio bean,以便它可以被任何類調用?我將它註冊到一個applicationContext.xml中 – hancock46

+0

使全局服務bean可用是困難的(不是不可能的),但它可能不是正確的做法。在「ProfileWindow」更改後顯示一些代碼。你如何獲得一個實例?你在構造函數中使用autowired字段嗎? (P.S.歡迎來到SO,當回覆某人的評論時,您可以使用@username,這樣他們會收到您的回覆通知) – Morfic

回答

0

如果你的類有一個注入成員,請確保類本身從ApplicationContext中實例化。例如,您可以使用context.getBean(ProfileWindow.class)創建實例,或者類實例本身是託管類的註釋成員。如果您用new實例化ProfileWindow類,則注入機制不起作用。

0

感謝所有,但我解決了使用vaadin Spring集成附加

<dependency> 
    <groupId>ru.xpoft.vaadin</groupId> 
    <artifactId>spring-vaadin-integration</artifactId> 
    <version>3.2</version> 
</dependency>