目录
在SpringBoot项目普通类中注入mapper或service接口

  在Spring Boot项目的普通类(使用@Component注解),需要依赖注入mapper或service接口时,出现空指针异常的解决方法

  1. 该类使用@Component注解
  2. 添加一个本类类型的静态字段
  3. 创建一个初始化方法,贴上@PostConstruct 标签,用于注入bean
  4. 依赖注入mapper或service接口
  5. 最后直接在普通类中调用即可
@Component    // 该类使用@Component注解
public class Tengxun {
@Autowired
private TokenMapper tokenMapper; // 依赖注入mapper或service接口

public static Tengxun tengxun; // 添加一个本类类型的静态字段

/**
* 创建一个初始化方法,贴上@PostConstruct 标签,用于注入bean
*/
@PostConstruct
public void init() {
tengxun = this;
tengxun.tokenMapper = this.tokenMapper;
}

/**
* 请最后直接在普通类中调用即可
*/
public void testToken(){
System.out.println(tengxun.tokenMapper.selectCount( null ));
System.out.println(tengxun.tokenMapper.selectBySchema("hotel"));
}
}
文章作者: Gadfly
文章链接: https://blog.gadfly.pub/2019/12/09/cheng-xu-she-ji/zai-springboot-xiang-mu-pu-tong-lei-zhong-zhu-ru-mapper-huo-service-jie-kou/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 牛虻的世界
打赏
  • 微信
  • 支付寶

评论