试想一个场景:在一个工具类中执行数据库操作,此时工具类中所有的方法都是static的,你用到的Mapper也比然是static,而然Spring正常情况下不支持注入静态属性,这时直接使用注入的Mapper会出现空指针错误,解决方式代码示例如下:

@Component
public class ChannalStatusUtil {
    
    @Autowired
    private ChannelMapper channelMapper111;
    private static ChannelMapper channelMapper;

    @PostConstruct
    public void init() {
        channelMapper = channelMapper111;
    }

    
    public static void refreshChannalStatus() {
        channelMapper.updateRunStatusById(1, 0);
    }
}

对以上代码注意点的说明:

  • @Component 注解不要漏掉。
  • 使用@Autowired注入一个正常的channelMapper111,并声明一个工具类方法中要使用的channelMapper。
  • 在@PostConstruct注解中,对channelMapper进行赋值。
  • 最后在静态方法refreshChannalStatus中就可以使用channelMapper操作数据库啦。

如果我的博客对你有帮助,欢迎进行评论✏️✏️、点赞👍👍、收藏⭐️⭐️,满足一下我的虚荣心💖🙏🙏🙏 。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐