I'm new to springboot and fiddling around with DI.
I'm having a Service
public class GreeterService {
private ObjectMapper objectMapper;
public GreeterService(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public String greeting() throws JsonProcessingException {
return objectMapper.writeValueAsString(new HelloData());
}
}
this Service is supposed to be created via @Configuration
@Configuration
public class Config {
@Bean
public GreeterService greeterService(@Autowired ObjectMapper objectMapper) {
return new GreeterService(objectMapper);
}
}
I get the following exception:
java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(Object)" because "this.objectMapper" is null
also making ObjectMapper @Autowired
on a field does not work e.g.
@Autowired ObjectMapper objectMapper;
@Bean
public GreeterService greeterService() {
return new GreeterService(objectMapper);
}
main entry in com.example.demo
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Controller
@GetMapping(path = "methodInject")
public Object methodInject(GreeterService greeterService) throws JsonProcessingException {
return greeterService.greeting();
}
Further info:
I added to main
System.out.println("Is " + beanName + " in ApplicationContext: " +
context.containsBean(beanName));
which returns:
Is objectMapper in ApplicationContext: true
Is greeterService in ApplicationContext: true