Spring整合web项目

一般获取bean的方法是在Servlet当中直接加载配置文件,获取对象,但是这样获取每一次都要加载ApplicationContext.xml文件,过于浪费资源。
在这里插入图片描述

存在问题

  • 每次请求都会创建一个Spring的工厂,这样浪费服务器资源,应该一个项目只有一个Spring的工厂。
  • 在服务器启动的时候,创建一个Spring的工厂。创建完工厂,将这个工厂类保存到ServletContext中,每次使用的时候都从ServletContext中获取。

解决方案

使用spring核心监听器ContextLoaderListener,配置监听器,直接在Action当中获取工厂。

  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>

contextConfigLocation:表示用于加载 Bean 的配置文件;这段配置是 Spring 集成 Web 环境的通用配置;一般用于加载除 Web 层的 Bean(如DAO、Service 等),以便于与其他任何Web框架集成。
contextConfigLocation:表示用于加载 Bean 的配置文件;
contextClass:表示用于加载 Bean 的 ApplicationContext 实现类,默认 WebApplicationContext 。

  1. 直接在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);
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值