博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解决静态static方法注入mapper无效问题
阅读量:4147 次
发布时间:2019-05-25

本文共 1108 字,大约阅读时间需要 3 分钟。

记录优化程序过程中遇见的一个问题~

//问题代码@Componentpublic class MethodTest{   @Autowired   private static JnMapper jnFeppMapper;//静态方法调用内部类必须定义为静态类   @Autowired   JnMsgMapper msgMapper;   public static void staticMethod(){        jnFeppMapper.selectById(null); //此时jnFeppMapper为null,报空指针   }   public void exampleMethod(){        msgMapper.selectById(null);   }}

解决方案【@PostConstruct】:

使用Java EE 5中引入注解@PostConstruct,位于javax.annotation包下。

//解决问题@Componentpublic class MethodTest{   @Autowired   private JnMapper jnFeppMapper;//静态方法调用内部类必须定义为静态类   @Autowired   JnMsgMapper msgMapper;   public static MethodTest methodTestUtils;   @PostConstruct   public void init(){       methodTestUtils = this;       methodTestUtils.jnFeppMapper = this.jnFeppMapper;        }   public static void staticMethod(){       methodTestUtils.jnFeppMapper.selectById(null); //此时可以正常调用   }   public void exampleMethod(){        msgMapper.selectById(null);   }}

说明:被@PostConstruct注解修饰的方法,在服务加载servlet的时候运行,并且只会执行一次。执行顺序: 父类静态变量或静态语句块–>子类静态变量或静态语句块->父类实例变量或初始化语句块–>父类构造方法->子类实例变量或初始化语句块->子类构造方法--> @Autowired -> @PostConstruct....->destroy->@PreDestroy

 

转载地址:http://xpiti.baihongyu.com/

你可能感兴趣的文章
C++中异常的处理方法以及使用了哪些关键字
查看>>
如何定义和实现一个类的成员函数为回调函数
查看>>
内存分配的形式有哪些? C++
查看>>
什么是内存泄露,如何避免内存泄露 C++
查看>>
栈和堆的空间大小 C++
查看>>
什么是缓冲区溢出 C++
查看>>
sizeof C++
查看>>
使用指针有哪些好处? C++
查看>>
引用还是指针?
查看>>
checkio-non unique elements
查看>>
checkio-medium
查看>>
checkio-house password
查看>>
checkio-moore neighbourhood
查看>>
checkio-the most wanted letter
查看>>
checkio-Xs and Os Referee
查看>>
VS2012敲代码技巧
查看>>
VS2012快捷键大全
查看>>
VS2012入门图文教程——第一个程序Hello World
查看>>
UML类图——学设计模式前必备知识
查看>>
C#接口-简单示例
查看>>