如何在servlet中获取spring创建的bean

时间:2023-03-09 21:44:26
如何在servlet中获取spring创建的bean
package com.yxf.controller;

import java.io.IOException;
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.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import com.yxf.bean.User;
import com.yxf.serviceImpl.LoginServiceImpl; /**
* Servlet implementation class Login
*/
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L; private ApplicationContext context; private LoginServiceImpl loginServiceImpl; private volatile int count = 0; public LoginController() {} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("----------get---------------");
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} @Override
public void init() throws ServletException {
context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
loginServiceImpl = (LoginServiceImpl)context.getBean("loginServiceImpl"); } }

注意init方法中的配置。