2017-07-28 74 views
0

目前,我试图通过使用从文档弹簧批启动的基本Web容器建议来让我的脚本到Tomcat服务器上运行https://docs.spring.io/spring-batch/reference/html/configureJob.html 剧本是正常工作的jar文件的修改之前的主类,但当我尝试将其转换为servlet时,我遇到的问题仅在启动服务器时启动,我的@PostConstruct。此代码设置application.properties到spring.batch.job.enabled=false并具有如何获得@Postconstruct与Web容器中的Spring批处理?

@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只能在控制器请求它时才能被调用?

+0

你的读者/作者应该是步骤或作业范围。显然你创造他们作为单身人士。但是你为什么在'@ PostConstruct'方法中做到这一点?没有这种需要... –

+0

你想用'@ PostConstruct'做什么?为什么使用它与常规的春季注释? –

+0

就是这样。我是新来的春天,不知道我到底想问什么,但StepExecutionListener与BeforeStep和AfterStep完美配合 –

回答

0

你需要使用

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

@PostConstruct使用applicationContext被加载后,初始化一次。 在你的情况下,你想在每次作业运行时都运行这个初始化(你不希望数据泄漏到不同的作业中,对吧?)