SpringBoot中静态类调用自动注入的Mapper

问题

在静态的方法中使用 Mybatis Mapper, SpringBoot注解@Autowired 是不行的。

解决方法

创建一个工具类,并且使用 @PostConstruct 注解 。

该注解会在类加载之前自动执行标识的方法,并在方法中把静态的类赋值给非静态的类。

工具类代码

@Component
public class StaticUtil {
    @Autowired
    private HumitureMapper humitureMapper;
    private static HumitureMapper staticHumitureMapper;

    @PostConstruct
    public void init() {
        staticHumitureMapper = humitureMapper;
    }

    public static HumitureMapper getStaticMapper() {
        return staticHumitureMapper;
    }
}

调用

@Autowired
StaticUtil humitureMapper;

HumitureMapper humitureMapper = StaticUtil.getStaticMapper();

参考文章

https://blog.csdn.net/XmanAron/article/details/100515820

消息盒子
# 您需要首次评论以获取消息 #
# 您需要首次评论以获取消息 #

只显示最新10条未读和已读信息