CDI中@ConversationScoped注解工作机制疑问及示例请求
关于@ConversationScoped的常见误解与正确示例
你遇到的问题核心在于同一个HTTP请求内,CDI容器只会注入一次@ConversationScoped bean实例。你的Servlet的doGet方法是在单个请求里完成了“开启对话→修改值→结束对话→重新开启对话”的全流程,容器不会因为你结束再开启对话就重新创建新的ConversationBean实例,所以原来的i值(1)会被保留下来。
@ConversationScoped的设计初衷是跨多个HTTP请求共享状态,而不是在同一个请求里切换对话状态。当对话结束后,只有当后续新的HTTP请求进来时,容器才会创建新的bean实例。
正确演示对话销毁效果的示例
1. 改造后的ConversationBean
用Integer类型替代int,更直观地看到值的重置(int默认值为0,Integer默认是null,能更清晰体现实例重建):
@ConversationScoped public class ConversationBean implements Serializable { private Integer i = 0; @Inject private Conversation conversation; public void startOrResumeConversation() { if (conversation.isTransient()) { conversation.begin(); } } public void increment() { i++; } public Integer getI() { return i; } public void endConversation() { if (!conversation.isTransient()) { conversation.end(); } } public String getConversationId() { return conversation.isTransient() ? "无(临时对话)" : conversation.getId(); } }
2. 处理多请求的Servlet
通过请求参数区分不同操作,模拟跨请求的对话生命周期:
@WebServlet("/conversation-test") public class ConversationTestServlet extends HttpServlet { @Inject private ConversationBean conversationBean; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String action = request.getParameter("action"); response.setContentType("text/plain;charset=utf-8"); PrintWriter out = response.getWriter(); switch (action) { case "init": // 开启对话并设置初始值 conversationBean.startOrResumeConversation(); conversationBean.increment(); out.println("✅ 对话已开启"); out.println("当前i值:" + conversationBean.getI()); out.println("对话ID:" + conversationBean.getConversationId()); // 将对话ID存入Cookie,供后续请求关联对话 response.addCookie(new Cookie("conv-id", conversationBean.getConversationId())); break; case "check": // 从Cookie获取对话ID,恢复现有对话 Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("conv-id".equals(cookie.getName())) { conversation.setId(cookie.getValue()); conversationBean.startOrResumeConversation(); break; } } } out.println("当前对话i值:" + conversationBean.getI()); out.println("对话ID:" + conversationBean.getConversationId()); break; case "reset": // 结束旧对话,开启新对话 conversationBean.endConversation(); conversationBean.startOrResumeConversation(); out.println("❌ 旧对话已销毁,新对话已开启"); out.println("新对话i值:" + conversationBean.getI()); // 清除旧对话的Cookie Cookie cookie = new Cookie("conv-id", null); cookie.setMaxAge(0); response.addCookie(cookie); break; default: out.println("请指定action参数:init/check/reset"); } } }
3. 测试步骤
- 访问
http://localhost:8080/你的应用名/conversation-test?action=init,输出i=1,同时浏览器会存储对话ID的Cookie。 - 访问
http://localhost:8080/你的应用名/conversation-test?action=check,输出i=1,验证跨请求保留对话状态。 - 访问
http://localhost:8080/你的应用名/conversation-test?action=reset,输出新对话的i=0,说明旧对话的bean已被销毁,新实例初始化完成。 - 再次访问
check,会看到新对话的i=0,确认旧资源已被完全清除。
内容的提问来源于stack exchange,提问作者user20660794
相关产品推荐
相关产品推荐

