I have a batch job written using Spring Batch
I have a config file below:
JavaScript
x
@Configuration
public class ObjectMapperConfig {
@Bean
public ObjectMapper objectMapper(){
return new ObjectMapper();
}
}
I have Json Line aggregator as below:
JavaScript
public class JsonLineAggregator<T> implements LineAggregator<T> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public String aggregate(final T item) {
String result = null;
try {
result = mapper.writeValueAsString(item);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
}
I want to inject objectMapper and don’t want to create it inside the JsonLineAggregator class. Any idea how can I implement it using DI ?
Advertisement
Answer
You can use @Autowired
annotation to inject the dependency in spring like this:
JavaScript
@Autowired
private final ObjectMapper mapper;
And Spring will inject the ObjectMapper bean created by you in ObjectMapperConfig
class