【发布时间】:2015-01-30 12:00:12
【问题描述】:
我是 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 方法中的文件名参数,但它仍然无法运行。例如,如果在项目目录(与配置相同的级别)下创建一个名为 jobs 的目录并将 xml 放在那里,然后将文件路径传递给 CommandLineJobRunner,如下所示:
CommandLineJobRunner.main(new String[]{"/jobs/fileWritingJob.xml", "LayeredMultiThreadJobTest"});
或者这个
CommandLineJobRunner.main(new String[]{"../jobs/fileWritingJob.xml", "LayeredMultiThreadJobTest"});
它不起作用。
但是当我尝试在 config 目录下创建一个子目录并将 fileWritingJob.xml 放在那里时,像这样
CommandLineJobRunner.main(new String[]{"configsubdir/fileWritingJob.xml", "LayeredMultiThreadJobTest"});
它运行。就好像 CommandLineJobRunner 只检查 config 目录。
我的想法不多了,谁能帮帮我?
更新:经过一番挖掘,感谢 Michael Minella 关于 ClassPathXmlApplicationContext 的建议,我能够将 xml 放在任何我想要的地方。我也咨询了这个页面Spring cannot find bean xml configuration file when it does exist和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");
}
非常感谢您的所有投入!
【问题讨论】:
标签: java xml spring-batch