SoFunction
Updated on 2025-03-04

Analysis of the causes of NullPointerException in Spring

Bean in Spring related to the cause of NullPointerException exception

Problem description

In the Spring framework, beans injected with @Autowired annotation can be accessed throughout the class, including in the class's fields, constructors, and methods.

If you try to access this injected bean outside of the class (such as in a static method or static initialization block), you will have problems because Spring's dependency injection is performed at the instance level and it will not handle static members.

If you try to access outside the class or in a static context, you will receive a NullPointerException because the bean is not initialized in this context.

as follows:

    @Autowired
    private BaiduMapProperties baiduMapProperties;
    private String ak = ();
    private String address = ();

Solution

To solve this problem, you have several options:

Avoid using injected beans in static methods:

  • Change the static method to an instance method
  • Or pass the required dependencies to the static method in other ways

Using Spring's ApplicationContext:

  • If you do need to access Spring-managed beans in a static context, you can get it through ApplicationContext.
  • However, this approach is generally not recommended because it breaks Spring's dependency injection principle and can make the code difficult to test and maintain.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.