Spring Web 获得ApplicationContext

package cn.itcast.e_web;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@WebServlet("/Demo1Servlet")
public class Demo1Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //如何获得spring容器
        //1 获得application域
        ServletContext sc = this.getServletContext();
        //2 调用工具方法从app域取出容器
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
    
        System.out.println(ac.getBean("user"));
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

猜你喜欢

转载自www.cnblogs.com/qingyundian/p/9084893.html