Spring的容器初始化以后怎么使用

现在在web.xml中配置了spring的监听器,这时当启动tomcat的时候,spring的容器
就会初始化,对spring的配置采用注解的方式,假设有一个@Component("quest")此时,spring的配置文件中只有一句

如果这时在测试类中需要用到quest对象,应该怎么获得quest这个bean

如果不在web.xml中配置监听器,而是手动获得spring容器,这个我会,应该是
ApplicationContext ctx = new ClassPathXmlApplicationContext("XXXX.xml");
然后
Quest quest = (Quest)ctx.getBean("quest");

现在就想让配置监听器有同样的作用,应该怎么做

WebApplicationContext ac = ContextLoader.getCurrentWebApplicationContext() ;你试试

从你的描述中,实在不知道你的情况,这样子很难给你正确的答案呀。
你是只使用了Spring?还是除了Spring还有别的框架?还是直接使用的Spring MVC?
条件不清楚无法给出答案。

我在网上搜索了一下,找到一个例子,也不知道你能不能弄出来,你看下,不知道有没有帮助。
.创建一个类并让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.

示例代码:

 

  import org.springframework.beans.BeansException;

  import org.springframework.context.ApplicationContext;

  import org.springframework.context.ApplicationContextAware;

  public class MyApplicationContextUtil implements ApplicationContextAware {

  private static ApplicationContext context;

  //声明一个静态变量保存

  public void setApplicationContext(ApplicationContext contex) throws BeansException {

  this.context=contex;

  }

  public static ApplicationContext getContext(){

  return context;

  }

  }

  2.在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.

  例:

  <!-- 这个bean主要是为了得到ApplicationContext 所以它不需要其它属性-->

  <bean class="org.ing.springutil.MyApplicationContextUtil"></bean>

  3.有了这个ApplicationContext之后我们就可以调用其getBean("beanName")方法来得到由Spring 管理所有对象.

你可以让spring配置文件中声明的一个bean 实现ApplicationContextAware接口 那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的

public void setApplicationContext(ApplicationContext context) throws BeansException

方法,获得ApplicationContext对象。 这样你就可以操作上下文内的bean了。