zoukankan      html  css  js  c++  java
  • 于工具类中@Autowired注入为NULL的问题记录

     

    记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @Component //把普通pojo实例化到spring容器中 0
     public class MyUtil{
         // 这里是需要注入的Service ①
        @Autowired
         private MyService myService;
         private static MyUtil myUtil;
         //初始化 ②
         @PostConstruct 
         public void init() {      
                  myUtil = this;
                  myUtil.myService = this.myService;
          }
           //调用 ③
          public static void insertParam(int id){
                  // 调用方法 ④
    myUtil.myService.testInsert("xxx");
          }
     }

    注释:0 将普通pojo实例化到容器中、如果无注解myUtil为null
              ① spring自动注入,如果在静态方法中调用此注入类的方法,发现注入为'null';这里不是因为spring未注入,而是被static方法给'清空'了,在无法先于static方法初始化时可以使用@PostConstruct进行初始化。
       (注:@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。)

               ②使用@PostConstruct注解的方法public void init()先给该类赋值,然后通过@Autowired注入进来。这样不会影响dao等service下面调用的注入。
       ③ static方法
       ④ 调用方法 myService现在是作为myUtil的属性

    参考

  • 相关阅读:
    RSDS pdb格式
    关于windbg报错"No symbols for ntdll. Cannot continue."问题
    WinDbg常用命令系列---.cmdtree
    正确创建本地C++发布构建PDBS
    PDB文件会影响性能吗?
    每个开发人员必须知道PDB文件知识
    Windbg妙用
    在x64计算机上捕获32位进程的内存转储
    为什么我的堆栈上会有奇怪的函数名?(关于符号的讨论)
    redis入门基础
  • 原文地址:https://www.cnblogs.com/jpfss/p/10839610.html
Copyright © 2011-2022 走看看