I got annotations mostly working in Tomcat. To try this out, install
OpenEJB into Tomcat as noted before and simply add @EJB and @Resource
annotations to your servlet fields. I added an very simply servlet-
samples application which can be checked out with:
svn co http://svn.apache.org/repos/asf/openejb/trunk/openejb3/
examples/servlet-samples
This is a completely standalone sample and should be an easy starting
point. One critical thing to note about the example is the use of
<scope>provided</scope> in the maven pom.xml file to stop maven from
including duplicate copies of the annotation classes into the web
application.
For those that don't want to download the code, here is it:
public class AnnotatedServlet extends HttpServlet {
@EJB private AnnotatedEJBLocal ejb;
@Resource private DataSource ds;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
ServletOutputStream out = response.getOutputStream();
out.println("@EJB=" + ejb);
if (ejb != null) {
out.println("@EJB.getName()=" + ejb.getName());
out.println("@EJB.getDs()=" + ejb.getDs());
}
out.println("@Resource=" + ds);
}
}
@Stateless
public class AnnotatedEJB implements AnnotatedEJBLocal {
@Resource private DataSource ds;
private String name = "foo";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DataSource getDs() {
return ds;
}
public void setDs(DataSource ds) {
this.ds = ds;
}
public String toString() {
return "AnnotatedEJB[name=" + name + "]";
}
}
public interface AnnotatedEJBLocal {
String getName();
void setName(String name);
DataSource getDs();
void setDs(DataSource ds);
}
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://
java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>OpenEJB Servlet Examples</display-name>
<servlet>
<servlet-name>AnnotatedServlet</servlet-name>
<servlet-
class>org.apache.openejb.examples.servlet.AnnotatedServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>AnnotatedServlet</servlet-name>
<url-pattern>/annotated/*</url-pattern>
</servlet-mapping>
</web-app>
I'm going to be tuning the code over the next couple of days, but it
generally works now. Let me know if you find any bugs, or most
importantly if it doesn't work as you would expect Tomcat to work.
One of my goals is to not violate any expectations of Tomcat users,
so if something stops working like is used to do, let me know ASAP.
The integration should feel like the Tomcat team wrote it themselves.
-dain