本文介绍了我们可以在同一EAR中跨Web应用程序共享CDI @ApplicationScoped bean实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有2个Web应用程序的JavaEE应用程序。我还具有另一个包含由 @ApplicationScoped

I have an JavaEE Application that has 2 web applications. I also have another library web module that contains common_bean that annotated by @ApplicationScoped

注释的common_bean的库Web模块。我的问题是:我可以共享吗

My question is: Can I share common_bean instance across the two web applications?

已更新-我做了测试

在Web App1(/ web1)

@WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {

@Inject
CommonBean commonBean;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    commonBean.setValue("Servlet1: " + System.currentTimeMillis() + "--" + commonBean);
}
}

在Web App2(/ web2)

@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {

@Inject
CommonBean commonBean;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    commonBean.setValue("Servlet2: " + System.currentTimeMillis() + "--" + commonBean);
}
}

结果


  • 如果我先运行/ Web1 / Servlet1,然后运行/ Web2 / Servlet2:

  • If I run /Web1/Servlet1 FIRST then Run /Web2/Servlet2:

/ Web1 / Servlet1 -------工作

/Web1/Servlet1 ------- Worked

/ Web2 / Servlet2 -------发生CDI异常失败

/Web2/Servlet2 ------- Failed with CDI exception

如果我先运行/ Web2 / Servlet2,然后运行/ Web1 / Servlet1 :(重新启动服务器,然后重新测试)

If I run /Web2/Servlet2 FIRST then Run /Web1/Servlet1: ( Restart server then re-test)

/ Web2 / Servlet2 -------工作

/Web2/Servlet2 ------- Worked

/ Web1 / Servlet1 -------发生CDI异常失败

/Web1/Servlet1 ------- Failed with CDI exception

任何评论!

推荐答案

我发现了问题。我喜欢在这里发布解决方案。它可能会帮助某人:

I found the issue. I like to post the solution here. It may help someone:

解决方案:将Web库模块配置为EAR Module Assembly(库jar模块)-这样,

The solution is: Configure the Web library module as EAR Module Assembly (Lib jar module) - By doing this, only instance of Common bean created and this instance will be shared across all web applications in the same EAR.

我不确定这是否是CDI规范,但是它确定CDI规范。在Glassfish& fly。

I am not sure this is a specification of CDI or NOT but it worked on both Glassfish & Wildfly.

这篇关于我们可以在同一EAR中跨Web应用程序共享CDI @ApplicationScoped bean实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 23:08