How does springboot resolve static call service to null

  • 2021-09-12 01:04:30
  • OfStack

springboot static calls service to null

@ PostConstruct annotation Many people think it is 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 @ PostConstruct modified method runs when the server loads Servlet and is executed only once by the server. PostConstruct executes after the constructor and before the init () method.

Normally we will use the @ PostConstruct annotation in the Spring framework. The annotation method is executed in the whole Bean initialization order:

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

Actual combat:

Invoke the method in Bean of dependency injection in a static method.


@Component
public class LeaveCode {
    @Autowired
    private IPlaLeaveApplyService plaLeaveApplyService;
    public static LeaveCode leaveCode;
    /**
     *  Solve  static Method invocation    Injecting service For null
     */
    @PostConstruct
    public void init(){
        leaveCode = this;
        leaveCode.plaLeaveApplyService = this.plaLeaveApplyService;
    }
 }

SpringBoot static class introduces service null pointer/NULL

After Spring is injected into service, the registered service can be used normally by non-static methods. At that time, when using static class reference, the static class static method will empty 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;
        userUtils.userService = this.userService;
    }
}

Use:


User user = userUtils.userService.getUser(loginCode);

Related articles: