如何在Web容器中使用Spring批处理获取@Postconstruct?

时间:2017-07-28 19:36:00

标签: spring-mvc spring-boot spring-batch

目前我正在尝试使用文档https://docs.spring.io/spring-batch/reference/html/configureJob.html中的spring-batch-boot的基本Web容器指南,让我的脚本在tomcat服务器上运行 在修改主类之前,脚本作为jar文件正常工作,但是当我尝试将其转换为servlet时,我的@PostConstruct仅在服务器启动时出现问题。此代码将application.properties设置为spring.batch.job.enabled=false并具有

的控制器
@Controller
public class JobLauncherController {
   @Autowired
   JobLauncher jobLauncher;

   @Autowired
   Job job;

   @RequestMapping("/jobLauncher.html")
   public void handle() throws Exception{
      jobLauncher.run(job, new JobParameters());
}

使用主应用程序启动tomcat的servlet为

@SpringBootApplication
@EnableBatchProcessing
public class BatchApplication extends SpringBootServletInitializer{

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(BatchApplication.class);
}

public static void main(String[] args) {

    SpringApplication.run(BatchApplication.class, args);

}

问题是我的工作使用自定义项目阅读器和编写者在使用@PostConstruct运行它之前对其进行初始化。它在服务器启动时运行@PostConstruct,这有助于初始化bean以进行写入。 我的项目读者/作者看起来像这样

public class CustomReader extends ItemStreamSupport implements ItemReader<Acct>, ResourceAwareItemReaderItemStream<Acct> {
    //basic autowiring
    private int nextAcctIndex;
    private List<Acct> acctsList = new ArrayList();

    @PostConstruct
    private void initialize() throws IOException {
        //logic to parse files
        acctsList = Collections.unmodifiableList(acctsList);
        nextAcctIndex = 0;
    }

    @Override
    public Acct read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        // System.out.println("Start Read");

        Acct nextAcct = null;
        if (nextAcctIndex < acctsList.size()) {
            nextAcct = acctsList.get(nextAcctIndex);
            nextAcctIndex++;
            //System.out.println(nextAcct);
        }

BatchConfiguration将大多数示例调用为所有示例 @Bean public IteamReader<Acct> CustomReader(){ return new CustomReader();}

我的问题是我是以错误的方式解决这个问题,还是有办法让它成为@PostConstruct只有在Controller请求时才能调用它?

1 个答案:

答案 0 :(得分:0)

你需要使用

@BeforeStep
public void beforeStep(StepExecution stepExecution) {
    init();
}

@PostConstruct用于在加载applicationContext后初始化一次。 在您的情况下,您希望每次作业运行时都运行此初始化(您不希望数据泄漏到不同的作业,对吗?)