I'm trying to inject a stateless EJB into servlet.
But it is not working. Did I understand something wrong?
If I do this in a @WebService
annotated class, I can use the injected EJB without problems.
My EJB:
@Stateless
public class doSomethingService
{
public void doSomething()
{
System.out.println("DO SOMETHING");
}
}
My Servlet:
@WebServlet("/testservlet")
public class test_servlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Inject
private doSomethingService injBean;
public test_servlet()
{
super();
injBean.doSomething();
}
This causes a NullPointerException
. I tried to do a JNDI-Lookup and it worked very well. Is it a fact that @Inject
does not work in Servlets?
Im using Glassfish 3.1.2.2
Example Application timer as explained in the EJB - Create Application chapter. Use Beans created in the EJB - Message Driven Bean chapter. Keep rest of the files unchanged. Clean and Build the application to make sure business logic is working as per the requirements.
You're trying to access it in the constructor. The injected dependencies are not available in the constructor. It's not possible to set an instance variable if the instance is not constructed yet. You're basically expecting it to work like this:
test_servlet servlet;
servlet.injBean = new doSomethingService();
servlet = new test_servlet();
This is clearly not the case. You can access it at earliest in init()
method of the servlet. It's also just available in any of the doXxx()
methods of the servlet.
To start, replace
public test_servlet() {
super();
injBean.doSomething();
}
by
@Override
public void init() {
injBean.doSomething();
}
Unrelated to the concrete problem, I strongly recommend to work on your Java naming conventions. The lowercased and underscored class names are not conform standard Java naming conventions, which slowdowns the interpreting of the code by seasoned Java developers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With