Spring @PostContruct没有等待完整的bean创建

时间:2016-04-19 20:07:33

标签: spring dependency-injection

在使用@PostConstruct设置服务以使用初始化方法时,我正在调用已自动装配的服务。我从该服务调用的方法依次使用已经自动装入的服务方法,但是当调用该服务时,我得到一个NPE。实际上,第二个服务中的所有自动连接字段都是null。拥有原始自动服务扩展ApplicationContextAware证明此服务尚未完全初始化(或至少未被上下文感知)。

似乎在我的服务已被提升为上下文之后调用@PostConstruct,但它不会等到应用程序的其余部分知道上下文。我怎么能让它等待所有依赖项或更改初始化,以便稍后在Spring的初始化路径中调用它?

示例:

@Service 
public class ServiceA {

  @Autowired 
  private ServiceB serviceB;

  @PostConstruct 
  public void init() {
    serviceB.someMethod();
  }
}

@Service 
public class ServiceB implements ApplicationContextAware {

  @Autowired 
  private ServiceC serviceC; // This is null at the time of   
  private ApplicationContext applicationContext;

  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext; // This never gets called
  }

  @PostConstruct
  public void someMethod() {
    serviceB.someOtherMethod(); // NullPointerException
  }
}

0 个答案:

没有答案