Since Servlet 3.0 it is possible to register Servlet instances programmatically with javax.servlet.ServletContext#addServlet
. This class has also a createServlet
method which analyses some annotations and performs dependency injection. I wonder if I need this method if I don't need the annotation processing. I'd like to have a servlet with a usual constructor to set required dependencies via dependency injection.
@Inject
public MyServlet(SomeDependency sd) { // Constructor
...
}
Questions:
- Is it possible to construct a servlet instance "by hand" without
createServlet
? (new MyServlet()
) - Is it possible to use the dependency injection mechanism of a Java EE server to perform constructor injection? How to do it? Or is a separate DI framework like Guice required?