Springboot+mybatis Service层使用@Autowired 注解 mapper对象爆红问题
[外链图片转存失败(img-6NSKmbsD-1569059397640)(E:\Users\FangJunXiong\Pictures\博客截图\批注 2019-09-21 172851.png)]
问题如上所述,这里提两点:
- 这个报错可能导致程序运行大面积爆红
- 这个报错会逼疯强迫症
解决方法:
-
为避免程序运行报错 ,需要在Application.class添加注解@MapperScan(mapper包位置)
@SpringBootApplication // 扫描包mapper注解 @MapperScan("com.linghangcloud.fegert.mapper") public class FegertApplication { public static void main(String[] args) { SpringApplication.run(FegertApplication.class, args); } }
-
以上修改避免了运行时异常,但是问题依旧。
解决方法在每个mapper类前加上@Repository注解
@Repository @Mapper//@Mapper注解 springbboot能否自动扫描识别 public interface UserMapper { }
其他并不靠谱的解决方法:
- 修改@Autowired 为@Autowired(required = false)
required=false 设置这个属性后,mapper对象就可以为null ,这样无形之中给自己挖了个坑
参考博客:
https://blog.csdn.net/sinat_36710456/article/details/80143986
https://blog.csdn.net/weixin_44678104/article/details/100111958