如何通过调用另一个 class 的方法来初始化最终字段?
How to initialize final field by calling method from another class?
一个 class 已声明服务的 RestitController
@Autowired
private RestitService restitService;
我想声明一个 class 变量(因为它会被 RestitController 的许多方法使用)并用 RestitService 方法的结果填充它。
问题是当我写类似
的东西时
private final HashMap<K, V> map = restitService.makeMap();
我得到 NullPointerException
因为此时 restitService
是 null
。
是否有其他方式来组织我的代码?我真的很想避免每次需要地图时都调用该方法。
感谢您的帮助,抱歉我的英语不好。
编辑:Luigi 的解决方案很好。
只有一件事:我的 HashMap 在我的代码中实际上是一个 WeakHashMap。该地图已在 Tomcat 开始时正确加载,但一旦调用使用它的方法,它就是空的。我将 class 更改为 HashMap,问题就消失了。猜猜垃圾收集器是这次不及时清理的幕后黑手。
使用构造函数注入
private RestitService restitService;
private final HashMap<K, V> map;
@Autowired
public RestitController(RestitService restitService) {
this.restitService = restitService;
this.map = restitService.makeMap();
}
您也可以使用@PostConstruct 方法来完成。
@Autowired
private RestitService restitService;
private final HashMap<K, V> map=new HashMap<K, String>();
@PostConstruct
public void initIt() throws Exception {
this.map.putAll(restitService.makeMap());
}
一个 class 已声明服务的 RestitController
@Autowired
private RestitService restitService;
我想声明一个 class 变量(因为它会被 RestitController 的许多方法使用)并用 RestitService 方法的结果填充它。
问题是当我写类似
的东西时private final HashMap<K, V> map = restitService.makeMap();
我得到 NullPointerException
因为此时 restitService
是 null
。
是否有其他方式来组织我的代码?我真的很想避免每次需要地图时都调用该方法。
感谢您的帮助,抱歉我的英语不好。
编辑:Luigi 的解决方案很好。 只有一件事:我的 HashMap 在我的代码中实际上是一个 WeakHashMap。该地图已在 Tomcat 开始时正确加载,但一旦调用使用它的方法,它就是空的。我将 class 更改为 HashMap,问题就消失了。猜猜垃圾收集器是这次不及时清理的幕后黑手。
使用构造函数注入
private RestitService restitService;
private final HashMap<K, V> map;
@Autowired
public RestitController(RestitService restitService) {
this.restitService = restitService;
this.map = restitService.makeMap();
}
您也可以使用@PostConstruct 方法来完成。
@Autowired
private RestitService restitService;
private final HashMap<K, V> map=new HashMap<K, String>();
@PostConstruct
public void initIt() throws Exception {
this.map.putAll(restitService.makeMap());
}