---
title: "spring2.0.8和activemq5.2 topic方式，消息被重复消费的问题找到原因"
author: "wmj2003"
date: "2009-09-10T14:24:00Z"
tags: []
slug: "spring2-0-8-activemq5-2-topic"
draft: false
lastmod: "2009-09-10T14:24:00Z"
id: 466238
url: "https://wmj2003.iteye.com/blog/466238"
---

找了好几个月，终于找到了问题的所在。

因为以前在后台的java类中重复加载了spring配置文件，导致topic的消费者被重复增加，所以一个消息被消费了两次。

 

package com.work.core.spring;

import javax.servlet.ServletContext;  
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;  
import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;

/\**  
 * 通过静态代码来获取spring的context，第一次调用的使用运行。  
 *  
 * @author wangmingjie  
 *  
 \*/  
public class MyBeanUtil {  
//因为下面的代码导致了activemqtopic订阅方式，每次都被消费了两次。  
   
//在非web环境中获取bean的方法。  
**// private static ApplicationContext context = new ClassPathXmlApplicationContext(**  
**//   "applicationContext\*.xml");**  
   
 private static ApplicationContext context ;

 public static ApplicationContext getContext() {  
  return context;  
 }

 /\**  
  * 通过权限管理QxglInitServlet来设置context  
  * @param context  
  \*/  
 public static void setContext(ApplicationContext context) {  
  MyBeanUtil.context = context;  
 }

 /\**  
  * 在应用程序中，获取到spring的beans对象。&lt;br&gt;  
  *  首先在QxglInitServlet中设置了context。  
  * @param beanName  
  * @return  
  \*/  
 public static Object getBean(String beanName) {  
  return context.getBean(beanName);  
 }

 /\**  
  * 在web环境中，通过WebApplicationContext来获取spring的bean。  
  * @param request  
  * @param beanName  
  * @return  
  \*/  
 public static Object getBean(HttpServletRequest request, String beanName) {  
  WebApplicationContext webApplicationContext = WebApplicationContextUtils  
    .getWebApplicationContext(request.getSession()  
      .getServletContext());  
  return webApplicationContext.getBean(beanName);  
 }  
   
 /\**  
  * 在web环境中，通过WebApplicationContext来获取spring的bean。  
  * @param context  
  * @param beanName  
  * @return  
  \*/  
 public static Object getBean(ServletContext context, String beanName) {  
  WebApplicationContext webApplicationContext = WebApplicationContextUtils  
    .getWebApplicationContext(context);  
  return webApplicationContext.getBean(beanName);  
 }   
}