2016-07-27 73 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