2016-07-27 78 views
0

我使用彈簧啓動vaadin project.I有這樣的倉庫:public interface PersonneRepository extends JpaRepository<Person, Integer>, JpaSpecificationExecutor {}春天開機vaadin項目@Autowired

我想在我的課。在用戶界面和瀏覽我這樣做是爲了實例化這個庫: @ Autowired PersonneRepository回購; 這個工作很容易,但在簡單的類(公共類x {}}回購空返回null。而我不喜歡它通過參數或會話。請問你有什麼想法嗎?

+0

東西得到的一類自動裝配的唯一途徑是,如果類本身最初的掃描過程中被創建。如果你手動創建SomeClass class = new SomeClass();自動裝配將無法正常工作!這可能是你的問題嗎? –

+0

是的,我創建我的類ith SomeClass class = new SomeClass();但是如何在初始掃描期間創建它? – FoufaFaFa

+0

如果你將它註釋爲「@ Component」(或「@ Service」或其它),那麼是的。你只需要弄清楚它應該有什麼'@範圍',因爲[默認它被設置爲單例](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans .html#beans-factory-scopes) – Morfic

回答

1

爲了注入依賴關係,依賴類必須由Spring來管理。這可以通過類註釋來實現@Component

指示註釋類是「組件」。當使用基於註釋的配置和類路徑掃描時,這些類被認爲是自動檢測的候選對象。

對於Vaadin類@SpringComponent使用它的建議:

別名{@link org.springframework.stereotype.Component},以防止{@link com.vaadin.ui.Component}衝突。

例子:

@Repository // Indicates that an annotated class is a "Repository", it's a specialized form of @Component 
public interface PersonRepository extends JpaRepository<Person, Long> { 
    // Spring generates a singleton proxy instance with some common CRUD methods 
} 

@UIScope // Implementation of Spring's {@link org.springframework.beans.factory.config.Scope} that binds the UIs and dependent beans to the current {@link com.vaadin.server.VaadinSession} 
@SpringComponent 
public class SomeVaadinClassWichUsesTheRepository { 

    private PersonRepository personRepository; 

    @Autowired // setter injection to allow simple mocking in tests 
    public void setPersonRepository(PersonRepository personRepository) { 
     this.personRepository = personRepository; 
    } 

    /** 
    * The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. 
    */ 
    @PostConsruct 
    public init() { 
     // do something with personRepository, e.g. init Vaadin table... 
    } 
} 
+0

非常感謝Mr Agassner,但是我怎樣才能訪問SomeVaadinClassWichUsesTheRepository和SomeVaadinClassWichUsesTheRepository x = new SomeVaadinClassWichUsesTheRepository()??? – FoufaFaFa

+1

注入它與自動裝配;) – agassner

+0

不,這種解決方案不適用於我:/ – FoufaFaFa