我尝试在我的 solrQueue 中添加任何内容时遇到空指针异常。我检查了调试器,这是因为 solrQueue 为空。但是我已经在我的应用程序上下文中 Autowiring 了它,那么为什么会出现这个错误呢?

public class Check { 
    @Autowired 
    public LinkedBlockingQueue<SolrInputDocument> solrQueue; 
    public SolrInputDocument solrDoc;    
    public void solradd(){ 
        solrDoc=new SolrInputDocument(); 
        solrDoc.addField("title", "abc"); 
        solrQueue.add(solrDoc);//solrQueue is null  
    } 
} 

应用程序上下文.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
        http://www.springframework.org/schema/aop  
        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
 
    <context:annotation-config /> 
    <!--<context:component-scan base-package="com/abc" />   --> 
 
    <bean id="solrQueue" class="java.util.concurrent.LinkedBlockingQueue" /> 
    <bean id="check" class="com.abc.Check" scope="prototype" /> 
 
</beans> 

请您参考如下方法:

您正在手动创建 Check 类的实例,而不是让 Spring 为您创建/返回一个实例:

Check c=new Check(); 
c.solradd(); 

这永远不会*工作,因为 Spring 不知道您创建了 Check 类。根据您如何启动 Spring 上下文,您必须显式询问应用程序上下文:

Check check = applicationContext.getBean(Check.class) 

或者将 check bean 注入(inject)到其他一些组件中,比如 Controller :

@Autowired 
private Check check; 

另见:

* AspectJ 编织可以解决问题,但这就像用大炮杀死苍蝇一样


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!