简体   繁体   English

CDI:使用@PostConstruct时@Inject不会失败

[英]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. 任何人都可以向我解释为什么第一种情况和第二种情况失败导致NullPointerException原因是,当第三种情况可以正常工作时,在Bean1的构造函数中b2和/或b3仍然为null。

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();
   }


}

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. 仅在实例化bean之后才进行注入,而在实例化构造函数之后才进行注入,这就是为什么在第一种情况下具有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. 在第二种情况下,您将实例化bean b2,这意味着它不会由Java EE服务器管理(这意味着没有注入),因此请参考ref。 b3 will be null. b3将为空。

In the third case, when your init method is called, all the constructors have been called and the beans have been injected. 在第三种情况下,当您的init方法被调用时,所有构造函数均已被调用,并且Bean已被注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM