执行spring bean时出现问题

时间:2016-04-21 08:58:40

标签: spring spring-mvc hadoop spring-data-hadoop

我有一个名为textFileWriter的bean,用于将字符串实体写入HDFS。我在bean配置文件中配置了spring bean。在执行时获取NullPointerException。请帮帮我。

我的bean配置: -

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/hadoop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:hdp="http://www.springframework.org/schema/hadoop" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">


    <hdp:configuration id="hadoopConfigBean">
        fs.defaultFS=${hdp.fs}
    </hdp:configuration>


    <beans:bean id="textFileWriter"
        class="org.springframework.data.hadoop.store.output.TextFileWriter">
        <beans:constructor-arg index="0" ref="hadoopConfigBean"></beans:constructor-arg>
        <beans:constructor-arg index="1"
            type="org.apache.hadoop.fs.Path" value="/user/mhduser"></beans:constructor-arg>
        <beans:constructor-arg index="2" type="org.springframework.data.hadoop.store.codec.CodecInfo" >
        <beans:null></beans:null>
        </beans:constructor-arg>
    </beans:bean>

    <context:property-placeholder location="hadoop-configs.properties" />
</beans:beans>

主类: -

public class MainApp {
    @Autowired
    TextFileWriter textFileWriter;

    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext(
                "/META-INF/spring/application-context.xml", MainApp.class); 
        System.out.println("Context loaded...");
        MainApp obj=new MainApp();
        obj.someMethod();

        context.registerShutdownHook();

    }

    private void someMethod() {
        try {
            textFileWriter.write("hi there");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

此行中出现空指针异常: -

textFileWriter.write("hi there");

2 个答案:

答案 0 :(得分:1)

@Autowired在这里工作没有成功,因为你正在使用一个新的类MainApp实例,这个实例不是由spring管理的,这就是为什么你得到{{1} }

NullPointerException

解决方法是:

    MainApp obj=new MainApp();
    obj.someMethod();

}

答案 1 :(得分:1)

您仍然可以在不明确添加Select to_timestamp(1408788007); -- 2014-08-23 10:00:07+00 作为bean的情况下使Spring注入依赖项。

  1. 启用注释驱动配置。添加到MainApp以下

    application-context.xml
  2. 使用

    创建Spring连接线
    <context:annotation-config />