SoFunction
Updated on 2025-03-08

springboot how to solve the static call service to null

springboot static call service as null

@PostConstruct annotation Many people think it was provided by Spring. Actually, it is Java's own annotation.

Description of this annotation in Java:

@PostConstruct This annotation is used to modify a non-static void() method. The method modified by @PostConstruct will run when the server loads the servlet and will only be executed by the server once. PostConstruct is executed after the constructor and before the init() method.

Usually we will use the @PostConstruct annotation in the Spring framework. The execution order of the annotation method in the entire bean initialization:

Constructor (construction method) -> @Autowired (dependency injection) -> @PostConstruct (annotated method)

Practical combat:

Call a method in a dependency-injected bean in a static method.

@Component
public class LeaveCode {
    @Autowired
    private IPlaLeaveApplyService plaLeaveApplyService;
    public static LeaveCode leaveCode;
    /**
      * Solve the static method call The injected service is null
      */
    @PostConstruct
    public void init(){
        leaveCode = this;
         = ;
    }
 }

SpringBoot static class introduces service null pointer/NULL

After Spring injects the service, under normal circumstances, non-static methods can use the registered service normally. When using a static class to reference, the static class static method will clear the service injected by spring.

How to solve the problem of referencing null pointers?

@Component
public class UserUtils {
    @Autowired
    private UserService userService;
    private static UserUtils userUtils;
 
    @PostConstruct
    public void init() {
        userUtils = this;
         = ;
    }
}

use:

User user = (loginCode);

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