Assuming you have a bean, limaBean, that you want to inject into a servlet, here is the applicationContext.xml:
<bean id="limaBean" class="com.example.LimaBeanImpl">
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="limaBeanInServletContext">
<ref bean="limaBean">
</ref>
</entry></map>
</property>
</bean>
The ServletContextAttributeExporter takes an existing managed bean, 'limaBean', and injects it into the ServletContext under the name 'limaBeanInServletContext'.
The servlet accesses this bean like:
public class DocumentViewerServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
LimaBean limaBean = getLimaBean();
limaBean.doSomething();
...
}
private DocumentService getLimaBean()
{
ServletContext servletContext = this.getServletContext();
return (LimaBean) servletContext
.getAttribute("limaBeanInServletContext");
}
}
At runtime, Spring will inject the bean and everything works.
The reason you wanted to inject the bean in the first place, though, was so that you could easily write a test that injects the bean.
Set the attribute on org.springframework.mock.web.MockServletConfig and pass that into the servlets init(ServletConfig) method.
public class VegetableServletTest extends TestCase
{
private VegetableServlet servlet = null;
private LimaBean fakeLimaBean = null;
protected void setUp() throws Exception
{
super.setUp();
servlet = new VegetableServlet();
fakeLimaBean = new FakeLimaBean();
MockServletConfig config = new MockServletConfig();
config.getServletContext().setAttribute("limaBeanInServletContext",
fakeLimaBean);
servlet.init(config);
}
}
1 comment:
Thanks dude... if it very helpful
Post a Comment