Vaadin 视图中的自动装配服务和组件不起作用

Ale*_*hev 1 java spring dependency-injection vaadin

各位程序员朋友们好!我对 Vaadin 比较陌生,所以请原谅我。我正在尝试将我的服务层自动连接到我的视图中,如下所示:

@Route("")
@PWA(name = "First time bruh", shortName = "Project Base")
public class MainView extends VerticalLayout {

    private TextField filterText = new TextField();
    private Grid<Customer> grid = new Grid<>(Customer.class);
    private CustomerForm customerForm = new CustomerForm(this);

    @Autowired
    private CustomerService customerService;
Run Code Online (Sandbox Code Playgroud)

并且 customerService 依赖项注入工作正常,但是当我尝试在组件中使用它时,它返回 null:

@Route
public class CustomerForm extends FormLayout {

    @Autowired
    private CustomerService customerService;
Run Code Online (Sandbox Code Playgroud)

我尝试用 @Component 和 @SpringComponent 注释类,但依赖注入不起作用,我认为问题不是来自类不是 bean 的事实,因为 MainView Class 也不是 bean。

我的愿望是我创建的自定义子组件可以访问服务层。

在此先感谢您的帮助!

Kas*_*rer 5

在 Vaadin UI 中,您只能在路由端点(具有@Route注释的视图)中注入,并且仅当通过导航到注释中指定的路由打开该视图时才可以注入。(因为只有那时该视图的实例化才能“自动”完成)。

经验法则:每当您使用new关键字自己实例化某些东西时,注入/自动装配都不起作用。

我对你的情况的理解是:
你有一个MainView,你想在其中添加一个CustomerForm.

以下是如何做到这一点:
注入CustomerServiceMainView,并通过CustomerService实例进入的构造CustomerForm

@Route
public class MainView extends VerticalLayout {
    public MainView(CustomerService customerService) { // customerService will be injected
        CustomerForm customerForm = new CustomerForm(customerService);
        add(customerForm);
    }
}

Run Code Online (Sandbox Code Playgroud)
public class CustomerForm extends FormLayout {
    public CustomerForm (CustomerService customerService){
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是制作CustomerForma @Component(记得在 spring 配置类中正确扫描它),将服务注入其中,然后将整个表单注入MainView

@Route
public class MainView extends VerticalLayout {
    public MainView(CustomerForm customerForm) {  // customerForm will be injected
        add(customerForm);
    }
}

Run Code Online (Sandbox Code Playgroud)
@Component
public class CustomerForm extends FormLayout {
    public CustomerForm (CustomerService customerService){ // customerService will be injected
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)