为了注入依赖关系,依赖类必须由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