1. 程式人生 > >springboot 專案普通類中呼叫mapper或service介面(utils包下的類封裝方法時呼叫mapper或service介面)

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);
            }
        }
    }