Can we share CDI @ApplicationScoped bean instance accross web application in the same EAR?

ぐ巨炮叔叔 提交于 2019-12-12 18:28:17

问题


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

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

Updated - I did the test

In 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);
}
}

In 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);
}
}

The Result

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

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

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

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

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

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

Any comments!


回答1:


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

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.

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



来源:https://stackoverflow.com/questions/28281314/can-we-share-cdi-applicationscoped-bean-instance-accross-web-application-in-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!