package com.blogspot.ostas.spring;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.blogspot.ostas.spring.beans.ClassWithSimpleBeanInjection;
import com.blogspot.ostas.spring.beans.SimpleBean;
public class MyServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(MyServlet.class.getName());
private ApplicationContext context = null;
//private SimpleBean simpleBean = null;
private ClassWithSimpleBeanInjection simpleBean = null;
@Override
public void init()
{
try
{
super.init();
context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
//singleton
//simpleBean = (SimpleBean) context.getBean("simpleBean");
//prototype
//simpleBean = (SimpleBean) context.getBean("simpleBeanPrototype");
//with injection
simpleBean = (ClassWithSimpleBeanInjection) context.getBean("classWithSimpleBeanInjection");
logger.info("Context started. servlet.init() called");
}
catch (ServletException e)
{
e.printStackTrace();
}
}
public MyServlet()
{
super();
logger.info("Servlet coustructor called");
}
private String s;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
simpleBean = (ClassWithSimpleBeanInjection) context.getBean("classWithSimpleBeanInjection");
s = simpleBean.injectedBeanMethodCall();
try
{
out.printf("%s\n", s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|