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

2024-11-30 01:57:43
推荐回答(1个)
回答1:

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");
}
}