Solving @inject null pointer exception

Getting a NullPointerException on @Inject ? In this post we’ll post a few possible solutions and things to check, that could explain the @inject null pointer exception.

Make sure your archive (jar, war, …) has a beans.xml file defined

The beans.xml file is known as the bean archive descriptor. Below you can find the most simple example with just a root beans xml element:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

This file should be placed into META-INF/beans.xml or WEB-INF/beans.xml.
If you don’t include this file in your module archive, CDI injection will not be active for this archive as the container will not scan the archive.

There are a few reasons why the spec was done this way:

  • Performance: The container only has to scan the modules where you’ve added the beans.xml
  • The beans.xml also lets you define interceptors and decorators that have to be executed when the injection takes place.

When using CDI in some places, you have to use it everywhere

In CDI, the container manages the lifecycle of the objects it creates via the @Inject. What this means is that if you bundle a bean with an injected dependency into another object, the other object also has to be managed by CDI. Doing a new OtherObject() will not work; at least the @Inject will not be done.

3 thoughts on “Solving @inject null pointer exception”

  1. Great tip. That was the exact problem for me. I was missing beans.xml and hence the beans were not inject in to my servlets. Thanks for the post.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.