本文共 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/