普通类调用service层或者mapper层接口

常见的是Controller层调用service层,调用mapper层。但是因为一些业务需求,可能需要在普通类中直接调用service层或者mapper层接口,这时候如果使用普通类直接调用service层或者mapper层都会报null,就算在对应的service或者mapper层添加注解@Component加入Spring容器管理也不行,原因在于调用的service或mapper层是非静态的,就算你设置为静态的也是错误的。

下面方法经过测试,是可以使用的

@Component 
public class TestUtils {
    
    @Autowired
    private MyMapper myMapper;
    
    public static TestUtils testUtils;
    
    @PostConstruct
    public void init() {    
        testUtils = this;
    } 
     
    public static void test(int id){
        //直接掉mapper接口是没问题的,不会报空指针
        testUtils.itemMapper.queryUserById(id);
    }
}

还有一种方法针对解决service层调用问题,可以直接通过new一个srvice层实现类解决,但是这种方法针对mapper这种接口的时候就不太友好了,推荐上述解决方案。

猜你喜欢

转载自blog.csdn.net/qq_40386113/article/details/109176900