I have a batch job written using Spring Batch
I have a config file below:
@Configuration public class ObjectMapperConfig { @Bean public ObjectMapper objectMapper(){ return new ObjectMapper(); } }
I have Json Line aggregator as below:
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:
@Autowired private final ObjectMapper mapper;
And Spring will inject the ObjectMapper bean created by you in ObjectMapperConfig
class