I can't figure out why all my beans are null in the controller. I understand that this is a common question but I am not instantiating the object with new
.
Controller:
@Controller
@RequestMapping("/store")
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/getOptions")
private String getOptions(HttpServletRequest request)
{
myService.doSomething(request);
....
}
}
When I request http://localhost/store/getOptions
I get a NullPointerException on myService
.
MyService
@Service
public class MyService
{
....
}
WebConfig
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
BeanNameUrlHandlerMapping beanNameUrlHandlerMapping()
{
return new BeanNameUrlHandlerMapping();
}
}
Main
@SpringBootApplication
@Configuration
@ComponentScan(basePackages = { "com.mypackage.config", "com.mypackage.service", "com.mypackage.controller"})
public class MyApplication
{
public static void main(String[] args)
{
if (AuthConfigFactory.getFactory() == null)
AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());
SpringApplication.run(MyApplication.class, args);
}
}
When I start the application, I can see in the logs that the myService
bean is actually being Autowired into the controller:
- Processing injected element of bean 'myController': AutowiredFieldElement for private com.mypackage.service.MyService com.mypackage.controller.MyController.myService
- Returning cached instance of singleton bean 'MyService'
- Autowiring by type from bean name 'myController' to bean named 'myService'
So I don't understand why when I try to access myService
within the controller, it is null. I do not instantiate the controller anywhere with new
.
Clipped Exception
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause:
java.lang.NullPointerException: null
at com.mypackage.controller.MyController.getOptions(MyController.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
....
Edit:
I've removed web.xml from my project, as it is irrelevant.