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
CodePudding user response:
add to Config
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
and write a simple test to see all beans in spring context
@SpringBootTest
class Demo1ApplicationTests {
@Autowired
ApplicationContext context;
@Test
void contextLoads() {
Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
}
}
CodePudding user response:
The code you pasted seems correct. The problem may be more global.
Do you run the whole thing as Spring Boot application (with proper main method)?
Do you call your service as spring bean? Service should also be autowired, not just java standard new instance.
Are your service and config classes in packages that gets scanned?