springboot 项目普通类中调用mapper或service接口(utils包下的类封装方法时调用mapper或service接口)

1、该类使用@Component注解

2、添加一个你需要用到的类的静态字段

3、创建一个初始化方法,贴上@PostConstruct 标签,用于注入bean

4、创建方法调用mapper或service接口

5、最后直接在普通类中调用即可

	//1
    @Component
    public class Judge {
    
        //2
        @Autowired
        private ProductMapper productMapper;
    
        public static Judge judge;
    
    	//3
        @PostConstruct
        public void init(){
            judge = this ;
            //4
            judge.productMapper = this.productMapper;
        }
    
    //你要封装的方法
        public static void judgeProductStatus(String a){
      	  //5
            String productStatus = judge.productMapper.findStatusById(a);
            if ("1".equals(productStatus)||productStatus == null)
            {
                throw new OrderException(ResultEnum.PRODUCT_NOT_EXIST);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_42337796/article/details/84865320