Arne Deutsch
Arne Deutsch

Reputation: 14779

@Inject seem not to work in JBoss AS 7

I have installed the latest JBoss AS 7 (7.0.2) and installed the eclipse tools to connect it with WTP. I created a "Dynamic Web Project" (without maven). I try to get a "HelloWorld" running. There are just two classes.

@WebServlet("/HelloWorld")
public class HelloWorldServlet extends HttpServlet {
    @Inject
    HelloService helloService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.println("<html><head /><body>");
        writer.println("<h1>" + helloService.createHelloMessage("World") + "</h1>");
        writer.println("</body></html>");
        writer.close();
    }
}

public class HelloService {
    public String createHelloMessage(String name) {
        return "Hello " + name + "!";
    }
}

I start the server from eclipse and it starts without errors. But when calling my servlet from the browser (localhost:8080) my code throws an NPE.

10:28:29,646 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/hello].[hello.HelloWorldServlet]] (http--127.0.0.1-8080-1) Servlet.service() for servlet hello.HelloWorldServlet threw exception: java.lang.NullPointerException
    at hello.HelloWorldServlet.doGet(HelloWorldServlet.java:23) [classes:]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
    [...]

Seems that the @Inject annotation does not work. How to track down the problem? What might be the cause?

Upvotes: 2

Views: 5122

Answers (1)

stratwine
stratwine

Reputation: 3701

A beans.xml file is required for bean discovery (and thereby for injection to work correctly) and in most cases just an empty beans.xml would do.

Some quick links:
Configuring a CDI Application
Why is beans.xml required in CDI?

Upvotes: 5

Related Questions