And we can see the NullPointerException in the logs of the server:
3.3 Why did this happen?
Although the field @myDao is @AutoWired in MyService,however,because we create instance of MyService by new instead of Spring, spring didn’t know about the instance of MyService and didn’t know to autowire it.
4 How to solve this problem?
4.1 DO NOT create instance by yourself
You should not create MyService instance by yourself, you can do as follows:
Let’s call the api:
Here we use the @Autowired to inject the instance of MyService, do not create the instance by new.
You can reference this quotes:
The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects’ dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.
The IoC container isn’t magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you–it never goes through the configuration process. There are three ways that you can get your beans configured.
If you use Spring framework in your application, just leave the class initialization to spring, do not create instances by yourself.