Spring Batch jdbcbatchitemwriter afterpropertiesset repeat trigger twice

569 views Asked by At

Why spring batch jdbcbatchitemwriter afterpropertiesset repeat trigger twice?

 @Autowired
 TestWriter write;

public Step startStep(StepBuilderFactory stepBuilders) {
        return stepBuilders.get("step")                
                .listener(new StepResultListener())
                .<Map, Map>chunk(chunkSize)
                .reader(....)
                .processor(....)
                .writer(write)
                .faultTolerant()
                .build();
    }

and TestWriter.java code is

@Bean(name = "write")
    @StepScope
    public JdbcBatchItemWriter<Map> write() {
        .....
        
        JdbcBatchItemWriter<Map> itemWriter = new JdbcBatchItemWriter<>();
        itemWriter.setDataSource(dataSource);
        itemWriter.setSql("insert into student (id,name) values (?,?) ");        
        ItemPreparedStatementSetter setter = new ItemPreparedStatementSetter() {
            @Override
            public void setValues(Object o, PreparedStatement preparedStatement) throws SQLException {
                ......
            }
        };
        itemWriter.setItemPreparedStatementSetter(setter);
        itemWriter.afterPropertiesSet();
        return itemWriter;
    }

I debug in JdbcBatchItemWriter afterpropertiesSet(), I found this function will call twice. Please tell me why? I want afterpropertiesSet() this function only call one.

1

There are 1 answers

0
Henning On

The method afterPropertiesSet is not specific to Spring Batch but is part of the underlying Spring Framework. If a class has such a method and an object of that class is exposed as a bean, Spring will call the method after it has set all properties of the object.

You should remove your invocation of the method from the factory bean method for the JdbcBatchItemWriter. Then it will we invoked only once by Spring.

You should only invoke the method yourself in situations when objects of a class that are expected to be used as beans (or expected to have afterPropertiesSet called) are not actually managed by Spring.