spring - UI.getCurrent 在 Spring Managed Bean 中返回 Null

标签 spring spring-boot vaadin vaadin4spring

目前,我尝试使用 Spring Boot 和 Vaadin 创建示例实现。我尝试在 spring 托管 bean 中初始化 vaadin 导航器,但因此我需要访问 UI 对象。

我实现了需要很多类和接口(interface)的 MVP 模式,但问题归结为以下示例代码:

@SpringUI
public class MyVaadinUI extends UI
{
    @Autowired
    private MainPresenter mainPresenter;

    protected void init(VaadinRequest request)
    {
       setContent(mainPresenter.getView());
    }
}

@UIScope
@SpringComponent
public class MainPresenterImpl implements MainPresenter
{
    @Autowired
    public MainPresenterImpl(MainModel model, MainView view)
    {
        super(model, view);
    }

    @PostConstruct
    public void init()
    {
       UI ui = UI.getCurrent();
       Assert.isNull(ui); // ui is always null
    }
}

我已经读到 UI 实例保存在 ThreadLocal 变量中。我可以通过调试来验证这一点。我不明白为什么有线 bean MainPresenter 在不同的线程中。这也不应该是范围问题。

到目前为止,应用程序运行良好,直到我尝试访问 Presenter 中的 UI 实例。

VAADIN wiki 没有帮助,我在这个论坛中找不到有用的答案。

最佳答案

几个小时后我可以自己回答这个问题。

此问题的解决方案是牢记初始化顺序:当 MainPresenterImpl@PostConstruct 时> 被调用时还没有 UI,并且 UI 尚未在 ThreadLocal 实例中注册。我这样解决了问题:

@SpringUI
public class MyVaadinUI extends UI
{
    @Autowired
    private MainPresenter mainPresenter;

    protected void init(VaadinRequest request)
    {
       mainPresenter.initAfterBeanCreation()
       setContent(mainPresenter.getView());
    }
}

@UIScope
@SpringComponent
public class MainPresenterImpl implements MainPresenter
{
    @Autowired
    public MainPresenterImpl(MainModel model, MainView view)
    {
        super(model, view);
    }

    @PostConstruct
    public void init()
    {
       UI ui = UI.getCurrent(); // ui is always null
    }

    public void initAfterBeanCreation()
    {
        UI ui = UI.getCurrent(); // now ui is not null
    }
}

关于spring - UI.getCurrent 在 Spring Managed Bean 中返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343238/

相关文章:

java - 变量的 Spring Boot 约定

java - Spring boot @ResponseBody 不序列化实体 id

Grails - 从 war 中运行时位于不同路径的图像

java - 在 Activity 中使用变量

java - Vaadin 8 非模态窗口 CloseListener - 通过在其外部单击关闭

java - Hibernate 使用 Uuid 生成

java - 未调用 Spring Security j_spring_security_check

java - 未接收 ApplicationEnvironmentPreparedEvent

java - 在 AWS 中更改 Spring Boot Web 应用程序的 application.properties

xml - 支持 XML 的 Spring Boot REST