春季启动vaadin项目@Autowired



我使用的是spring-boot-vadin项目。我有一个这样的存储库:public interface PersonneRepository extends JpaRepository<Person, Integer>, JpaSpecificationExecutor {}

我想在我的类中实例化这个存储库。在Ui和Views中,我这样做:@自动连线PersonneRepository回购;这很容易,但在简单类(公共类x{})中repo返回null。我不喜欢在参数或会话中传递它。你知道吗?

要注入依赖项,依赖类必须由Spring管理。这可以通过类注释@Component:来实现

指示带注释的类是"组件"。当使用基于注释的配置和类路径扫描时,这些类被认为是自动检测的候选者。

对于Vaadin类@SpringComponent,建议使用:

{@link org.springframework.costereot.Component}的别名,以防止与{@link.com.vadin.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...
    }
}

最新更新