Caucho Technology

dependency-injection servlet configuration

Resin allows servlets to be configured using dependency injection.


With Resin, servlets can use Java Bean-style configuration. A "Java Bean" is just a Java class that follows a simple set of rules. Each configuration parameterfoohas a corresponding setter methodsetFoowith a single argument for the value. Resin can look at the class using Java's reflection and find thesetFoomethod. Because Resin can find the bean-style setters from looking at the class, it can configure those setters in a configuration file like the web.xml.

Files in this tutorial

WEB-INF/web.xmlConfigures the Servlet with bean-style init
WEB-INF/classes/test/HelloServlet.javaThe servlet implementation.


The followingHelloServletservlet is a trivial bean-style servlet. Instead of hardcoding the "Hello, world" string, it lets the web.xml configure the string asgreeting. To make that work,HelloWorldadds a bean-stylesetGreeting(String)jmethod.

package test;


import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  private String _greeting = "Default";

  public void setGreeting(String greeting)
    _greeting = greeting;

  public void doGet (HttpServletRequest req,
                     HttpServletResponse res)
    throws ServletException, IOException
    PrintWriter out = res.getWriter();



Theservletconfiguration sets thegreetingproperty inside aninit/servlettag. After Resin instantiates the servlet object, it looks at the configuration file for any <init> section. Resin then calls asetXXXmethod for each<xxx>tag in <init>. In this case, Resin will callsetGreeting

Resin will perform any type conversion necessary, so you can use integers and doubles as well as strings. After Resin calls thesetXXXmethods, it will call theinit(ServletConfig)method.

When Resin initializes the servlet, it will make the following calls:

  1. servlet = new test.HelloServlet();
  2. servlet.setGreeting("Hello, World!");
  3. servlet.init(servletConfig);
<web-app xmlns=""
    <ee:WebServlet urlPatterns="/hello"/>

    <test:greeting>Hello, bean-style World</test:greeting>


Copyright © 1998-2011 Caucho Technology, Inc. All rights reserved.
Resin ® is a registered trademark, and Quercustm, Ambertm, and Hessiantm are trademarks of Caucho Technology.