通过JobParameter在Spring Batch中设置属性文件

时间:2013-08-29 16:12:16

标签: java spring spring-batch

我在Spring Batch项目中有三个不同的.properties文件,我正在尝试设置哪个.properties文件应该用作JobParameter。我希望能够像这样开展工作:

java CommandLineJobRunner context.xml jobName region=us

该区域应指定应使用哪个.properties文件。问题是让上下文识别JobParameter。我试过以下无济于事:

<context:property-placeholder location="classpath:batch.#{jobParameters['region']}.properties"/>

还有:

<util:properties id="batchProperties" location="classpath:batch.#{jobParameters['region']}.properties"></util:properties>

我听说添加scope =“step”可以修复类似的问题,但我尝试将其添加到上述两个解决方案中,但仍然有例外。

我想我错过了一个基本的想法,为什么我不能让这个工作,但我无法弄清楚这个想法是什么。

如果有人对此工作有任何建议和/或解释我以前的方法失败的原因,我会很感激。

1 个答案:

答案 0 :(得分:4)

这不是正确的方法(你不可能做你想做的事) 您必须认为jobParameters仅在作业正在运行时才可用,并且只有标记为scope="step"(而非<context:property-placeholder><util:properties>的作文步骤才有{{1} }}}。属性 解决问题的一种方法是在第一步使用侦听器运行之前在作业的执行上下文中加载属性文件:

step
你的job.xml中的

public class PropertyLoaderJobExecutionListener extends StepExecutionListenerSupport {
  Properties countryProperties;

  public void setCountryProperties(Properties pfb) {
    this.countryProperties = pfb;
  }

  @Override
  public void beforeStep(StepExecution stepExecution) {
    super.beforeStep(stepExecution);
    // Store property file content in jobExecutionContext with name "batchProperties"
    stepExecution.getJobExecution().getExecutionContext().put("batchProperties", countryProperties);
  }
}

并在第一步注册此侦听器(您不能在<bean id="loadPropertiesListener" class="PropertyLoaderJobExecutionListener" scope="step"> <property name="pfb"> <bean class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:batch.#{jobParameters['region']}.properties" /> </bean> </property> </bean> 中执行此操作,因为现在没有JobExectionListsner.beforeJob()scope="job"值的后期绑定是不可用)。

要使用spEL访问数据,请使用以下语法:

#{jobParameters['region']}

或更好的语法来访问属性(IDK spEL很好,很抱歉)。

希望明确并有助于解决您的问题。

编辑(我工作的job.xml的完整代码):

#{jobExecutionContext.get('batchProperties').getProperty('language')}