一般获取bean的方法是在Servlet当中直接加载配置文件,获取对象,但是这样获取每一次都要加载ApplicationContext.xml文件,过于浪费资源。
存在问题
- 每次请求都会创建一个Spring的工厂,这样浪费服务器资源,应该一个项目只有一个Spring的工厂。
- 在服务器启动的时候,创建一个Spring的工厂。创建完工厂,将这个工厂类保存到ServletContext中,每次使用的时候都从ServletContext中获取。
解决方案
使用spring核心监听器ContextLoaderListener,配置监听器,直接在Action当中获取工厂。
- 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>
contextConfigLocation:表示用于加载 Bean 的配置文件;这段配置是 Spring 集成 Web 环境的通用配置;一般用于加载除 Web 层的 Bean(如DAO、Service 等),以便于与其他任何Web框架集成。
contextConfigLocation:表示用于加载 Bean 的配置文件;
contextClass:表示用于加载 Bean 的 ApplicationContext 实现类,默认 WebApplicationContext 。
- 直接在Action当中获取工厂
service:
@Service
public class HelloService {
public String hello(String name) {
return "hello " + name;
}
}
@WebServlet("/SpringWebServlet")
public class servlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
HelloService hello = (HelloService) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean(HelloService.class);
String youyuan = hello.hello("youyuan");
System.out.println(youyuan);
}
}