12.3 依赖注入

JSR-352主要基于Spring Batch的编程模型。因此,尽管没有明确需要正式的依赖注入实现, 但还是推荐使用 DI 的方式。Spring Batch支持 JSR-352 中定义的三种加载组件方式:

  • 实现专用加载器 - Spring Batch 构建于 Spring 之上, 支持在 JSR-352 批处理作业中使用依赖注入.

  • 归档文件加载器 - JSR-352 定义了一个现有的 batch.xml 文件, 对逻辑name和实际的类名之间做了映射。这个文件必须放在 /META-INF/ 目录中才会生效。

  • 线程上下文类加载器(Thread Context Class Loader) - JSR-352 允许在 JSL 中通过内联的方式指定全限定类名来配置批处理组件. Spring Batch 也支持 JSR-352 的这种配置作业的方式.

要在 JSR-352的作业中使用Spring依赖性注入, 需要在 Spring application context 中将组件配置为 bean。bean 定义以后, 作业就可以像 batch.xml 中定义的部分 一样引用他们。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://xmlns.jcp.org/xml/ns/javaee
  7. http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd">
  8. <!-- javax.batch.api.Batchlet implementation -->
  9. <bean id="fooBatchlet" class="io.spring.FooBatchlet">
  10. <property name="prop" value="bar"/>
  11. </bean>
  12. <!-- Job is defined using the JSL schema provided in JSR-352 -->
  13. <job id="fooJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
  14. <step id="step1">
  15. <batchlet ref="fooBatchlet"/>
  16. </step>
  17. </job>
  18. </beans>

Spring 的 contexts (imports, etc) 组装在 JSR-352 中和其他地方的使用基本一样。唯一的区别是上下文定义的入口点在 /META-INF/batch-jobs/ .

要使用线程上下文类加载器的方式, 只需要提供全限定类名作为 ref 即可。要注意的是, 在使用这种方式 或者 batch.xml 时, 引用的类需要有一个无参构造函数来创建bean。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <job id="fooJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
  3. <step id="step1" >
  4. <batchlet ref="io.spring.FooBatchlet" />
  5. </step>
  6. </job>