springboot 如何解决static调用service为null
@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。
Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
实战:
在静态方法中调用依赖注入的Bean中的方法。
@Componentpublic 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清空。
造成引用空指针的情况,如何解决呢?@Componentpublic 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);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
1. Vue实现动态样式的多种方法汇总2. Vue看了就会的8个小技巧3. Python 解析简单的XML数据4. SpringBoot整合Redis的步骤5. 关于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服务传输的问题6. Vue Element前端应用开发之界面语言国际化7. SpringBoot+MQTT+apollo实现订阅发布功能的示例8. python 网页解析器掌握第三方 lxml 扩展库与 xpath 的使用方法9. python 如何将带小数的浮点型字符串转换为整数10. Python3.8 + Tkinter: Button设置image属性不显示的问题及解决方法

网公网安备