LHA
LHA

Reputation: 9655

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

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

Any comments!

Upvotes: 2

Views: 898

Answers (1)

LHA
LHA

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

Related Questions