Reputation: 9655
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!
Upvotes: 2
Views: 898
Reputation: 9655
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.
Upvotes: 2