Spring Batch Processor没有运行ItemProcessorListener

时间:2016-08-15 07:06:54

标签: java spring spring-batch listeners

所以我在Spring Batch 3.0.7.RELEASE和Spring 4.3.2.RELEASE中遇到问题,其中监听器未在我的ItemProcessor类中运行。 @StepScope级别的常规注入适用于@Value("#{jobExecutionContext['" + Constants.SECURITY_TOKEN + "']}"),如下所示。但它不适用于beforeProcessbeforeStep,我已尝试过注释版本和界面版本。我几乎100%肯定这是在某个时候工作,但无法弄清楚为什么它会停止。

有什么想法吗?看起来我配置错了吗?

AppBatchConfiguration.java

@Configuration
@EnableBatchProcessing
@ComponentScan(basePackages = "our.org.base")
public class AppBatchConfiguration {

    private final static SimpleLogger LOGGER = SimpleLogger.getInstance(AppBatchConfiguration.class);

    private final static String OUTPUT_XML_FILE_PATH_PLACEHOLDER = null;
    private final static String INPUT_XML_FILE_PATH_PLACEHOLDER = null;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean(name = "cimAppXmlReader")
    @StepScope
    public <T> ItemStreamReader<T> appXmlReader(@Value("#{jobParameters[inputXmlFilePath]}")
    String inputXmlFilePath) {
        LOGGER.info("Job Parameter => App XML File Path :" + inputXmlFilePath);
        StaxEventItemReader<T> reader = new StaxEventItemReader<T>();
        reader.setResource(new FileSystemResource(inputXmlFilePath));
        reader.setUnmarshaller(mecaUnMarshaller());
        reader.setFragmentRootElementNames(getAppRootElementNames());
        reader.setSaveState(false);

        // Make the StaxEventItemReader thread-safe
        SynchronizedItemStreamReader<T> synchronizedItemStreamReader = new SynchronizedItemStreamReader<T>();
        synchronizedItemStreamReader.setDelegate(reader);

        return synchronizedItemStreamReader;
    }

    @Bean
    @StepScope
    public ItemStreamReader<JAXBElement<AppIBTransactionHeaderType>> appXmlTransactionHeaderReader(@Value("#{jobParameters[inputXmlFilePath]}")
    String inputXmlFilePath) {
        LOGGER.info("Job Parameter => App XML File Path for Transaction Header :" + inputXmlFilePath);
        StaxEventItemReader<JAXBElement<AppIBTransactionHeaderType>> reader = new StaxEventItemReader<>();
        reader.setResource(new FileSystemResource(inputXmlFilePath));
        reader.setUnmarshaller(mecaUnMarshaller());

        String[] fragmentRootElementNames = new String[] {"AppIBTransactionHeader"};
        reader.setFragmentRootElementNames(fragmentRootElementNames);
        reader.setSaveState(false);

        return reader;
    }

    @Bean
    public Unmarshaller mecaUnMarshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setPackagesToScan(ObjectFactory.class.getPackage().getName());
        return marshaller;
    }

    @Bean
    public Marshaller uberMarshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setClassesToBeBound(ServiceRequestType.class);
        marshaller.setSupportJaxbElementClass(true);
        return marshaller;
    }

    @Bean(destroyMethod="") // To stop multiple close calls, see: http://stackoverflow.com/a/23089536
    @StepScope
    public ResourceAwareItemWriterItemStream<JAXBElement<ServiceRequestType>> writer(@Value("#{jobParameters[outputXmlFilePath]}")
    String outputXmlFilePath) {
        SyncStaxEventItemWriter<JAXBElement<ServiceRequestType>> writer = new SyncStaxEventItemWriter<JAXBElement<ServiceRequestType>>();

        writer.setResource(new FileSystemResource(outputXmlFilePath));
        writer.setMarshaller(uberMarshaller());
        writer.setSaveState(false);
        HashMap<String, String> rootElementAttribs = new HashMap<String, String>();
        rootElementAttribs.put("xmlns:ns1", "http://some.org/corporate/message/2010/1");
        writer.setRootElementAttributes(rootElementAttribs);
        writer.setRootTagName("ns1:SetOfServiceRequests");

        return writer;
    }

    @Bean
    @StepScope
    public <T> ItemProcessor<T, JAXBElement<ServiceRequestType>> appNotificationProcessor() {
        return new AppBatchNotificationItemProcessor<T>();
    }

    @Bean
    public ItemProcessor<JAXBElement<AppIBTransactionHeaderType>, Boolean> appBatchCreationProcessor() {
        return new AppBatchCreationItemProcessor();
    }


    public String[] getAppRootElementNames() {        
        //get list of App Transaction Element Names        
        return AppProcessorEnum.getValues();         
    }

    @Bean
    public Step AppStep() {
        // INPUT_XML_FILE_PATH_PLACEHOLDER and OUTPUT_XML_FILE_PATH_PLACEHOLDER will be overridden 
        // by injected jobParameters using late binding (StepScope)
        return stepBuilderFactory.get("AppStep")
                .<Object, JAXBElement<ServiceRequestType>> chunk(10)
                .reader(appXmlReader(INPUT_XML_FILE_PATH_PLACEHOLDER))
                .processor(appNotificationProcessor())
                .writer(writer(OUTPUT_XML_FILE_PATH_PLACEHOLDER))
                .taskExecutor(concurrentTaskExecutor())
                .throttleLimit(1)
                .build();

    }

    @Bean
    public Step BatchCreationStep() {
        return stepBuilderFactory.get("BatchCreationStep")
                .<JAXBElement<AppIBTransactionHeaderType>, Boolean>chunk(1)
                .reader(appXmlTransactionHeaderReader(INPUT_XML_FILE_PATH_PLACEHOLDER))
                .processor(appBatchCreationProcessor())
                .taskExecutor(concurrentTaskExecutor())
                .throttleLimit(1)
                .build();
    }

    @Bean
    public Job AppJob() {
        return jobBuilderFactory.get("AppJob")
                .incrementer(new RunIdIncrementer())
                .listener(AppJobCompletionNotificationListener())
                .flow(AppStep())
                .next(BatchCreationStep())
                .end()
                .build();
    }

    @Bean
    public JobCompletionNotificationListener AppJobCompletionNotificationListener() {
        return new JobCompletionNotificationListener();
    }

    @Bean
    public TaskExecutor concurrentTaskExecutor() {
        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
        taskExecutor.setConcurrencyLimit(1);
        return taskExecutor;
    }
}

AppBatchNotificationItemProcessor.java

@StepScope
public class AppBatchNotificationItemProcessor<E> extends AppAbstractItemProcessor<E, JAXBElement<ServiceRequestType>> implements ItemProcessor<E, JAXBElement<ServiceRequestType>>, StepExecutionListener {

    // This is populated correctly
    @Value("#{jobExecutionContext['" + Constants.SECURITY_TOKEN + "']}")
    private SecurityToken securityToken;

    @Autowired
    private AppProcessorService processor;

    @Override
    public JAXBElement<ServiceRequestType> process(E item) throws BPException {
        // Do Stuff
        return srRequest;
    }

    @BeforeProcess
    public void beforeProcess(E item) {
        System.out.println("Doesn't execute");
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        // Doesn't execute
        System.out.println("Doesn't execute");
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        // Doesn't execute
        System.out.println("Doesn't execute");
    }

}

2 个答案:

答案 0 :(得分:1)

这是因为您在@Bean方法中返回接口而不是实现。恕我直言,你应该在Spring中使用java配置时返回最具体的类型。原因如下:

通过XML进行配置时,您将在XML配置中提供该类。这将实现暴露给Spring,以便可以适当地发现和处理类实现的任何接口。使用java配置时,@Bean方法的返回类型用作该信息的替代。而且存在问题。如果您的返回类型是一个接口,Spring只知道该特定接口,而不是实现可能实现的所有接口。通过返回具体的具体类型,您可以让Spring了解您实际返回的内容,以便更好地处理各种注册和布线用例。

对于您的具体示例,由于您返回ItemProcessor并且它的步长范围(因此代理),所有Spring都知道ItemProcessor接口所期望的方法/行为。如果您返回实现(AppBatchNotificationItemProcessor),则可以自动配置其他行为。

答案 1 :(得分:0)

据我记忆,如果你使用StepScope,你必须直接在步骤上注册一个阅读器,编写器,处理器。

StepScope可以防止框架找出什么样的接口。 @annotations(例如@ BeforeProcess)代理实际上实现/定义,因此它无法将其注册为监听器。

所以,我假设添加

    return stepBuilderFactory.get("AppStep")
            .<Object, JAXBElement<ServiceRequestType>> chunk(10)
            .reader(appXmlReader(INPUT_XML_FILE_PATH_PLACEHOLDER))
            .processor(appNotificationProcessor())
            .writer(writer(OUTPUT_XML_FILE_PATH_PLACEHOLDER))

        .listener(appNotificationProcessor())

            .taskExecutor(concurrentTaskExecutor())
            .throttleLimit(1)
            .build();

它会起作用。