2017-05-25 143 views
0

我遇到以下情况,我正在运行到空指针异常,因为bean未初始化并导致失败,导致我的服务器无法启动。 在PostConstruct注释的方法中有一个新引入的调用失败。另一种不在PostConstruct中的方法正在执行相同的调用,该方法正确执行并且不会引起任何问题。Spring bean未注入

@Component 
@Lazy 
@Primary 
class Parent{ 
@Autowired 
private DesignContextService designContextService; 

@PostConstruct 
private void init(){ 
     designContextService.getMethod();// fails 
} 

private void someFunction(){ 
     designContextService.getMethod();// executes successfully 
} 
} 

} 

Class DesignContextService{ 
@Autowired 
private ContextService contextService; 

public void getMethod(){ 
    contextService.isContextCreated(); 
    ... 
} 
// Below classes present in another jar 
class ContextService{ 
    @Inject 
    public ContextAdapter contextAdapter; 

    public void isContextCreated(){ 
    contextAdapter.isEstablished();// contextAdapter is null . Throws exception here 

} 

} 

} 

错误堆栈跟踪:

at 
Caused by org.springframework.beans.factory.BeanCreationException : Error creating bean ... 

at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137) 



at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409) 

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620) 
+0

是'Parent'定义为一个Spring bean?依赖注入只适用于Spring bean,不适用于不是Spring bean的其他类。另外,当你使用'new'创建类的实例时,它不起作用;你需要让Spring管理这些bean。 – Jesper

+0

是的。我将纠正示例代码。 – jetty

+0

'class DesignContextService'也应该用'@Service'或'@ Component'注释,以便Spring能够正确自动装载它。也许这是你的问题? – mingos

回答

0

这是因为@Lazy注释。如文档中所述:

ApplicationContext实现的默认行为是在启动时急切地预先实例化所有的singleton bean。预实例化意味着一个ApplicationContext会急切地创建和配置所有的单例bean作为其初始化过程的一部分。一般来说,这是一件好事,因为这意味着配置或周围环境中的任何错误都会立即被发现(相对于可能的几小时甚至几天)。

请查看以下链接以供参考:Using Spring @Lazy and @PostConstruct annotations

Spring: how to initialize related lazy beans after main bean creation

+0

试图删除懒惰的注释。这个问题没有解决。 :( – jetty