工具类无法自动注入bean

@Component //把普通pojo实例化到spring容器中 0
public class MyUtil{
     // 这里是需要注入的Service
     @Autowired
     private MyService myService;
     private static MyUtil myUtil;
     /**
      * 没有这个方法会报空指针,因为还没注入完成就被注册到speing容器中了 ,所以这里用一个局部变量保存注入内容,直接使用局部变量
      * 
      * 执行顺序: construct>>PostConstruct>>static  所以在static中使用的对象都是在PostConstruct里提前组装好的
      */
     @PostConstruct
     public void init() {      
          myUtil = this;
          myUtil.myService = this.myService;
      }
     
     public static void insertParam(int id){
          // 调用方法
          myUtil.myService.testInsert("xxx");
      }
}

 

posted @ 2020-02-05 21:44  一千年以后1412  阅读(1279)  评论(0编辑  收藏  举报