spring batch 注入bean时在setmapper阶段能得到能得到bean的实例 writter阶段不能 5C

setMapper :

 package com.Mapper;
import java.util.Map;

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

import com.Entity.*;
import com.Service.CommonCSVService;
import com.Util.DateUtil;

@Component
public class CsvSetMapper implements FieldSetMapper<UserEntity>{

    @Autowired(required=true)
    @Qualifier("commonCSVService")
    //@Autowired(required=false)
    private CommonCSVService commonCSVService;

    int lineNumber=1;

    Map<String, String> csvFileNameMap;

    String csvFilePathAndName;
    @Override
    public UserEntity mapFieldSet(FieldSet fieldSet) throws BindException {
        // TODO Auto-generated method stub

        UserEntity user;
        try{
            csvFileNameMap =commonCSVService.getJobParams();
            csvFilePathAndName =csvFileNameMap.get("csvFilePathAndName");
            System.err.println(csvFilePathAndName);

            //csv的结束行为9时 就不再继续读取了  可以用来统计文件的总行数(我这里不包括字段标记行)
            if(fieldSet!=null&&!fieldSet.readString(0).equals("9")){
                user =new UserEntity();
                user.setRecordType(fieldSet.readString(0));
                user.setLineNumber(lineNumber);
                user.setName(fieldSet.readString(1));
                user.setBirthday(DateUtil.parseDate(fieldSet.readString(2)));
                user.setChildren(fieldSet.readInt(3));
                lineNumber++;
                return user;
            }
              lineNumber=1;
        }catch (Exception ex){
            System.out.println("mapFieldSet :"+ex);
        }
        return null;
    }

}

这里的commonCSVService不会报空指针
writer:

 package com.writer;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.Entity.UserEntity;
import com.Service.CommonCSVService;

@Component
public class CsvItemWriter implements ItemWriter<UserEntity> {

    @Autowired(required =true)
     @Qualifier("commonCSVService")
    //@Resource(name="commonCSVService1")
    //@Autowired(required=false)
    private CommonCSVService commonCSVService;



    @Override
    public void write(List<? extends UserEntity> users){
        try{
            for(UserEntity user :users){
                System.out.println(user.getName()+"!!!!!!!!!!!!!!!!!!!!!");
                if(commonCSVService.insertToDB(user)){
                    System.out.println("CsvItemWriter :"+" insert successfully!");
                }else{
                    System.out.println("CsvItemWriter :"+" insert failed !");
                }
            }
        }catch(Exception e){
            System.out.println("CsvItemWriter: "+e);
        }
    }

}

运行到if(commonCSVService.insertToDB(user)){
commonCSVService报空指针 这个用debug看过

这是配置文件


    <import resource="classpath:database-set.xml"/>
    <import resource="classpath:loadFilepath.xml"/>

    <!-- For consider the using of annotations foe defining Spring Bean -->
    <context:annotation-config /> 

    <!-- For defining Spring Bean -->
    <context:component-scan base-package="com" />
</beans>

以及service实现类:

 package com.Service.Impl;

import java.util.HashMap;
import java.util.Map;

import com.Entity.UserEntity;
import com.Service.CommonCSVService;

import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("commonCSVService")
//@Service
public class CommonCSVServiceImpl implements  CommonCSVService{

    public JobParameters jobParameters;

    public String csvFilePath;

    public String csvFileName;

    JobExecution jobExecution;

    @Autowired
    JobLauncher  jobLauncher;

    @Autowired(required = false)
    private JobRepository jobRepository;

    @Override
    public Map<String, String> getJobParams() {
        // TODO Auto-generated method stub
        Map<String,String> jobParamsMap =null;
        try{
            jobParamsMap =new HashMap<String,String>();
            jobParamsMap.put("time", jobParameters.getString("time"));
            jobParamsMap.put("filePath",jobParameters.getString("filePath"));
            jobParamsMap.put("csvFileName", jobParameters.getString("csvFileName"));
            jobParamsMap.put("csvFilePathAndName", jobParameters.getString("csvFilePathAndName"));

        }catch(Exception e){
            System.out.println("CommonCSVServiceImpl.getJobParams :"+e);
        }
        return jobParamsMap;
    }

    @Override
    public boolean insertToDB(UserEntity item) {
        // TODO Auto-generated method stub
        System.out.println(item.getName()+" ---------!!!!!!!!!!!!!!!!!!!!!!!!!");
        System.out.println("INSERT TO DB!!!!!!!!!!!!!!!!!!!!!!!!!!");
        return true;
    }

    @Override
    public boolean callCSVJob(Job job,String csvFilePath,String csvFileName) {
        // TODO Auto-generated method stub
        jobParameters=null;
        this.csvFilePath=csvFilePath;
        this.csvFileName=csvFileName;
        String  csvFilePathAndName=csvFilePath+csvFileName;
        jobParameters = new JobParametersBuilder()
        .addLong("time", System.currentTimeMillis())
        .addString("filePath", csvFilePath)
        .addString("csvFileName", csvFileName)
        .addString("csvFilePathAndName",csvFilePathAndName)
        .toJobParameters();

        try {
            jobExecution=jobLauncher.run(job, jobParameters);

            if(jobExecution.getStatus() == BatchStatus.COMPLETED){
                return  true;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return false;
    }

}

求大神解答下 困惑我很久了 感激不尽

4个回答

你差点配置就是配置文件你要配置一下数据的流向,就是set->writer的数据流向,这样writer中才会有数据

 <batch:job id="xxxxxJob">
        <batch:step id="xxxxxStep">
            <batch:tasklet>
                <batch:chunk reader="xxxxxReader" processor="xxxxxProcessor" writer="xxxxxWriter"
                             commit-interval="1000"/>
            </batch:tasklet>
        </batch:step>
    </batch:job>

airfling
airfling reader="xxxxxReader" processor="xxxxxProcessor" writer="xxxxxWriter" 这三个都是配置好的bean的名称
2 年多之前 回复
airfling
airfling reader,processor
2 年多之前 回复


<!-- For consider the using of annotations foe defining Spring Bean -->
<context:annotation-config /> 

<!-- For defining Spring Bean -->
<context:component-scan base-package="com" />

都不是 我是使用的注解版的 springbatch 因为在项目中也是这样的 我是没看到 在使用注解 注入writer时 没有写注解@Bean @Stepscope
相当于writer并没有注入到容器中 所以它类中的bean 也就没有bean实例 很尴尬 今早才看到
不过还是谢谢各位的解答 我也学到一些东西

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问