我遇到以下情况,我正在运行到空指针异常,因为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)
是'Parent'定义为一个Spring bean?依赖注入只适用于Spring bean,不适用于不是Spring bean的其他类。另外,当你使用'new'创建类的实例时,它不起作用;你需要让Spring管理这些bean。 – Jesper
是的。我将纠正示例代码。 – jetty
'class DesignContextService'也应该用'@Service'或'@ Component'注释,以便Spring能够正确自动装载它。也许这是你的问题? – mingos