Reputation: 39
I am using spring boot vaadin project.I have a repository like this:public interface PersonneRepository
extends JpaRepository<Person, Integer>, JpaSpecificationExecutor {}
I want to instantiate this repository in my class .In Ui and in Views I do this: @Autowired PersonneRepository repo; this work easily but in simple class(public class x{}) repo return null .And I don't like to passe it in parameter or session .Have you any idea please?
Upvotes: 0
Views: 1382
Reputation: 689
To inject dependencies the dependent classes have to be managed by Spring. This can be achieved with the class annotation @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.
For use in Vaadin classes @SpringComponent
it's recommended:
Alias for {@link org.springframework.stereotype.Component} to prevent conflicts with {@link com.vaadin.ui.Component}.
Example:
@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...
}
}
Upvotes: 2