1. 程式人生 > >Spring+Servlet整合(如何向Servlet註入屬性)

Spring+Servlet整合(如何向Servlet註入屬性)

servlet註入

package com.orm.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

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;

public class TestServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private ILoginService loginService;

private ApplicationContext applicationContext;


public void init(ServletConfig config) throws ServletException {

super.init(config);

applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

loginService= (ILoginService) applicationContext.getBean("loginService");

}

}


唯一不同的地方是需要在init()方法中手動到得需要註入屬性的bean,其它與正常開發流程一樣。



Spring+Servlet整合(如何向Servlet註入屬性)