我是 Spring Batch 框架的初学者,我发现了易于理解的代码http://www.javabeat.net/introduction-to-spring-batch/ http://www.javabeat.net/introduction-to-spring-batch/用作学习工具。我在 Eclipse 中设置了与页面中的代码类似的项目,如下所示:
并且代码使用 CommandLineJobRunner 执行 fileWritingJob.xml 中的作业,如下所示:
package net.javabeat.articles.spring.batch.examples.filewriter;
import org.springframework.batch.core.launch.support.CommandLineJobRunner;
public class Main {
public static void main(String[] args) throws Exception {
CommandLineJobRunner.main(new String[]{"fileWritingJob.xml", "LayeredMultiThreadJobTest"});
}
}
它按预期运行,没有问题。但是,当我将 fileWritingJob.xml 移动到另一个目录(仍在项目目录下)时,它不会运行。我尝试使用相对路径和完整路径更改 CommandLineJobRunner 方法中的文件名参数,但它仍然无法运行。例如,如果在项目目录(与 config 同一级别)下创建一个名为 jobs 的目录并将 xml 放在那里,然后将文件路径传递给 CommandLineJobRunner,如下所示:
CommandLineJobRunner.main(new String[]{"/jobs/fileWritingJob.xml", "LayeredMultiThreadJobTest"});
or this
CommandLineJobRunner.main(new String[]{"../jobs/fileWritingJob.xml", "LayeredMultiThreadJobTest"});
它不起作用。
但是当我尝试在 config 目录下创建一个子目录并将 fileWritingJob.xml 放在那里时,如下所示
CommandLineJobRunner.main(new String[]{"configsubdir/fileWritingJob.xml", "LayeredMultiThreadJobTest"});
它运行。就好像 CommandLineJobRunner 仅检查配置目录。
我没有想法了,有人可以帮助我吗?
更新:经过一番挖掘后,感谢 Michael Minella 关于 ClassPathXmlApplicationContext 的建议,我可以将 xml 放在我想要的任何地方。我也咨询过这个页面当bean xml配置文件确实存在时,Spring找不到它 https://stackoverflow.com/questions/12893760/spring-cannot-find-bean-xml-configuration-file-when-it-does-exist and http://www.mkyong.com/spring-batch/spring-batch-hello-world-example/ http://www.mkyong.com/spring-batch/spring-batch-hello-world-example/
所以我现在要做的是使用 ClassPathXmlApplicationContext 声明一个新上下文,然后使用作业启动器运行它,具体方法如下:
public static void main(String[] args) {
String[] springConfig =
{
"file:/path/to/xml/file"
};
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("JobName");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
非常感谢您的所有投入!