爲了注入依賴關係,依賴類必須由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...
}
}
東西得到的一類自動裝配的唯一途徑是,如果類本身最初的掃描過程中被創建。如果你手動創建SomeClass class = new SomeClass();自動裝配將無法正常工作!這可能是你的問題嗎? –
是的,我創建我的類ith SomeClass class = new SomeClass();但是如何在初始掃描期間創建它? – FoufaFaFa
如果你將它註釋爲「@ Component」(或「@ Service」或其它),那麼是的。你只需要弄清楚它應該有什麼'@範圍',因爲[默認它被設置爲單例](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans .html#beans-factory-scopes) – Morfic