spring beanfactory servletcontext

为了避免手动创建BeanFactory,spring在开启contextListener后会将beanFactory放入servletContext中。

 

具体操作步骤如下:

1、在web.xml中加入如下配置:

<context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext-*.xml</param-value>
  </context-param>
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

 

2、其实此时如果仅用action之类的,完全可以不管BeanFactory的创建或者调用了,因为spring会自动去管理了。

但是假如我们自己写了一个POJO需要引用spring中的bean时,就还得必须引用beanFactory了,引用方法也相当简单,见如下语句:

BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());

 

 

 =====================================================

注:在application下加载beanfactory的语句:

 

BeanFactory  factory=new ClassPathXmlApplicationContext("SpringHelloWorld.xml");

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(servletContext)