• @PostConstruct和static静态块初始化的区别


    static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .

    Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized
    译文:static模块会被引入,当class加载后。你的component组件的依赖还没有初始化。这就是为什么你的代码块会报空指针异常。(你的依赖都是null)

    1,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,

    为此,可以使用@PostConstruct注解一个方法来完成初始化,

    @PostConstruct注解的方法将会在依赖注入完成后被自动调用。

    2,执行优先级高于非静态的初始化块,它会在类初始化(类加载的初始化阶段)的时候执行一次,执行完成便销毁,它仅能初始化类变量,即static修饰的数据成员。

    初始化失败:

    static {
    strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
       System.out.println("初始化完成" + strategyMap.size());
    }

    初始化成功:

    @PostConstruct
    void init() {
    strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
    System.out.println("初始化完成" + strategyMap.size());
    );
    }
  • 相关阅读:
    微信小程序入门实例
    textarea 的value值以及演示
    Think php (TP5) 批量删除全部源码
    Think php TP5 CURD 增删改查全部源码
    TP5 Think php 批量添加全部源码
    centos7 supervisor管理redis
    Centos7 设置redis开机自启
    Centos7安装gearman和php扩展
    nginx-403
    FFmpeg-截取视频图片
  • 原文地址:https://www.cnblogs.com/hbuuid/p/13144611.html
Copyright © 2020-2023  润新知