我正在使用spring boot vaadin项目。我有一个这样的存储库:public interface PersonneRepository
extends JpaRepository<Person, Integer>, JpaSpecificationExecutor {}
我想在我的类中实例化这个存储库。在Ui和Views中我这样做: @Autowired PersonneRepository repo; 这项工作很容易,但在简单的类(公共类x {})repo返回null。我不喜欢在参数或会话中将它传递。请问有什么想法吗?
答案 0 :(得分: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...
}
}