软件编程
位置:首页>> 软件编程>> java编程>> springboot 如何解决static调用service为null

springboot 如何解决static调用service为null

作者:离别又见离别  发布时间:2022-09-05 05:30:03 

标签:springboot,static,service,null

springboot static调用service为null

@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。

Java中该注解的说明:

@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:

Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

实战:

在静态方法中调用依赖注入的Bean中的方法。


@Component
public class LeaveCode {
   @Autowired
   private IPlaLeaveApplyService plaLeaveApplyService;
   public static LeaveCode leaveCode;
   /**
    * 解决 static方法调用  注入的service为null
    */
   @PostConstruct
   public void init(){
       leaveCode = this;
       leaveCode.plaLeaveApplyService = this.plaLeaveApplyService;
   }
}

SpringBoot 静态类引入service 空指针/NULL

Spring注入service后,正常情况下非静态方法是可以正常使用注册的service的,当时用静态类引用的时候,静态类static方法会将spring注入的service清空。

造成引用空指针的情况,如何解决呢?


@Component
public class UserUtils {
   @Autowired
   private UserService userService;
   private static UserUtils userUtils;

@PostConstruct
   public void init() {
       userUtils = this;
       userUtils.userService = this.userService;
   }
}

使用:


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

来源:https://blog.csdn.net/weixin_43861630/article/details/109101869

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com