Spring 带有 JobParameters 的批处理 SQL 命令

Spring Batch SQL Command with JobParameters

我是 spring-batch 的新手,在这里我使用以下 reader 语句从数据库中获取一些数据。这里我需要动态传递值(通过参数)。

<bean id="ItemReader"
            class="org.springframework.batch.item.database.JdbcCursorItemReader">
            <property name="dataSource" ref="dataSource" />
            <property name="sql">
                <value>
                <![CDATA[
    select * from table where section = #{jobParameters['section']}
    ]]>
                </value>
            </property>
            <property name="rowMapper">
                <bean class="xyzRowMapper" />
            </property>
        </bean>

JUnit 代码:

JobParameters jobParameters = = new JobParametersBuilder()
                    .addString("section", section);

有人可以帮忙吗?

如官方 Spring 批处理文档的 §5.4 Late Binding of Job and Steps Attributes 中所述,您需要将 scope="step" 添加到步骤中:

Using a scope of Step is required in order to use late binding since the bean cannot actually be instantiated until the Step starts, which allows the attributes to be found. Because it is not part of the Spring container by default, the scope must be added explicitly, either by using the batch namespace or by including a bean definition explicitly for the StepScope (but not both)

给这个:

<bean id="ItemReader" scope="step" class="org.springframework.batch.item.database.JdbcCursorItemReader">
    <property name="dataSource" ref="dataSource" />
    <property name="sql">
        <value>
            <![CDATA[
                select * from table where section = #{jobParameters['section']}
            ]]>
        </value>
    </property>
    <property name="rowMapper">
        <bean class="xyzRowMapper" />
    </property>
</bean>