自动装配LinkedBlockingQueue时出现空指针异常 [英] Null Pointer Exception while Autowiring LinkedBlockingQueue

查看:298
本文介绍了自动装配LinkedBlockingQueue时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试在solrQueue中添加任何内容时,我得到了空指针异常.我检查了调试器,这是因为solrQueue为空.但是我已经在应用程序上下文中对其进行了自动布线,那么为什么会出现此错误?

I am getting null pointer exception while trying to add anything in my solrQueue. I checked in debugger and it is because solrQueue is null. But I have autowired it in my application context then why this error?

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 
    }
}

应用Context.xml

application Context.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为您创建/返回一个实例:

You are creating an instance of Check class manually rather than asking Spring to create/return one for you:

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

由于Spring不了解您创建的Check类,因此这永远不会*.根据如何启动Spring上下文,您必须明确询问应用程序上下文:

This will never* work since Spring has no knowledge about you created Check class. Depending on how do you start you Spring context, you must either explicitly ask the application context:

Check check = applicationContext.getBean(Check.class)

或将check bean注入到其他类似控制器的组件中:

or inject the check bean into some other compoent like controller:

@Autowired
private Check check;

另请参见:

  • Spring依赖注入自动装配为空
  • See also:

    • Spring Dependency Injection Autowiring Null
    • * AspectJ编织将达到目的,但这就像使用大炮杀死苍蝇

      这篇关于自动装配LinkedBlockingQueue时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆