我是 Spring Batch Framework 的初学者,我从 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 只检查配置目录。
我的想法用完了,谁能帮帮我?
更新:在深入研究之后,感谢 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");
}
非常感谢您的所有意见!
最佳答案
有关将基于 xml 的作业定义的路径传递给 CommandLineJobRunner
时发生的情况的一些细节。我们所做的就是将该字符串传递给 ClassPathXmlApplicationContext
的构造函数。因此,作业定义的 xml 文件应该位于应用程序的类路径中。我无法从您的项目屏幕截图中看出您是如何构建项目的,因此我不确定配置目录是否在您的类路径中。但是,如果它位于类路径中并且位于类路径的根目录下,我希望您能够将路径作为 "/config/fileWritingJob.xml"
传递到 fileWritingJob.xml。
此类的源代码在调试此类问题时会很有帮助。您可以在此处找到 CommandLineJobRunner
的源代码:https://github.com/spring-projects/spring-batch/blob/master/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/CommandLineJobRunner.java
关于java - Spring Batch CommandLineJobRunner 找不到 .xml 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27246040/