Spring 启动 vaadin 项目@Autowired

Spring boot vaadin project @Autowired

我正在使用 spring boot vaadin project.I 有这样的存储库:public interface PersonneRepository extends JpaRepository<Person, Integer>, JpaSpecificationExecutor {}

我想在我的 class 中实例化此存储库。在 Ui 和视图中,我这样做: @Autowired PersonneRepository 回购; 这项工作很容易,但很简单 class(public class x{}) repo return null 。我不喜欢在参数或会话中传递它。你有吗有什么想法吗?

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

来实现

Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

在 Vaadin 中使用 classes @SpringComponent 建议:

Alias for {@link org.springframework.stereotype.Component} to prevent conflicts with {@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...
    }
}