今天在项目中有一个需求,就是在静态工具类中注入service进行操作,在网上查找了一下,但是一直报空指针异常java.lang.NullPointerException!最后解决了此问题,和大家分享一下。
第一步:首先上代码,和网上的一样。
@Component
public class QiniuUtil {
@Autowired
private AppService appService;
private static QiniuUtil qiniuUtil;
@PostConstruct
public void init(){
qiniuUtil = this;
qiniuUtil.appService = this.appService;
}
public static String upload(MultipartFile file){
List<App> app = qiniuUtil.appService.findAll();
System.out.println(app.toString());
}
第二步:在spring.xml 中添加
<!-- 扫描utils层注解 -->
<context:component-scan base-package="com.sky.utils" />
最后在重启tomcat即可!
本文介绍如何在静态工具类中注入Spring管理的Service组件,并实现其功能调用。通过使用@Component注解及@PostConstruct初始化方法,配合Spring配置文件的设置,成功解决了静态工具类注入Service时出现的空指针异常。
522

被折叠的 条评论
为什么被折叠?



