Search code examples
javacdi

Does CDI work for regular Java application?


I have simple maven project with three classes. In my META-INF I have my empty beans.xml. Everytime I run my Main.java I get a NullPointerException.

Exception in thread "main" java.lang.NullPointerException
at hom.World.helloWorld(World.java:12)
at hom.Main.main(Main.java:6)

Is what I'm trying to accomplish is way out of scope of what CDI is suppose to do?

Hello.java

package hom;
import javax.enterprise.inject.Default;

@Default
public class Hello {
   public String hello() {
      return "Hello ";
   }
}

World.java

package hom;
import javax.enterprise.inject.Default;
import javax.inject.Inject;

@Default
public class World {
   @Inject
   Hello hello;

   public String helloWorld() {
      return hello.hello() + "World!";
   }
}

Main.java

package hom;
public class Main {
   public static void main(String[] args) {
      World helloWorld = new World();
      System.out.println(helloWord.helloWorld());
   }
}

Solution

  • It is possible to use CDI in a standalone application.

    Weld weld = new Weld();
    WeldContainer container = weld.initialize();
    World helloWorld = container.instance().select(World.class).get();
    System.out.println(helloWorld.helloWorld());
    weld.shutdown();
    

    You will also need the weld-se dependency.

    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>2.2.4.Final</version>
    </dependency>
    

    See also Weld documentation on the subject.