spring在非controller里使用service层的注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Honnyee/article/details/85338186

       在SpringMVC框架中,经常要使用@Autowired注解注入Service接口,在controller层中注入service接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果在自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,注入的bean会为空,报空指针异常!

       解决方法:

在要使用的工具类里,进行如下操作

在要使用的工具类里,进行如下操作

1.将这个类@component注册,在spring application文件里加上扫描

2.autowire注入service层方法

3.使用注解 @PostConstruct 初始化一个构造器 this指向当前实例

代码如图:

然后就可以调用service的方法了

 

猜你喜欢

转载自blog.csdn.net/Honnyee/article/details/85338186