Search code examples
javaejbcdi

CDI : @Inject not failing when using @PostConstruct


Can anybody explain to me why the first and the second case fail causing NullPointerException because b2 and/or b3 is/are still null in the constructor of Bean1,when the third case work fine.

Having this in all the cases :

@Stateless
public class Bean2 {

   @Inject
   private Bean3 b3; 

   public Bean2(){

   }

}

First case : (Failure)

@Singleton
@StartUp
public class Bean1 {

   @Inject
   private Bean2 b2;

   public Bean1(){
     b2.someMethod(); // b2 throws null pointer exception
   }

}

Second case : (Failure)

@Singleton
@StartUp
public class Bean1 {

   private Bean2 b2;

   public Bean1(){
     b2 = new Bean2();
     b2.someMethod(); // b3 throws null pointer exception
   }

}

Third case : (Success)

@Singleton
@StartUp
public class Bean1 {

   @Inject
   private Bean2 b2;

   public Bean1(){

   }

   @PostConstruct
   public init(){
     b2.someMethod();
   }


}

Solution

  • Injection only occurs after the bean has been instantiated, which occurs after your constructor has been called, that's why in the first case you have a NPE.

    In the second case you instantiate yourself the bean b2 which implies that it will not be managed by the Java EE server (that means no injection) so ref. b3 will be null.

    In the third case, when your init method is called, all the constructors have been called and the beans have been injected.