【发布时间】:2022-10-25 03:10:20
【问题描述】:
我在服务中设置缓存,然后调用该服务来检索缓存,如下所示:
MenuService(用@Service 注释)这是设置缓存的地方
@Autowired
APIClient apiClient \\feign client calling to another api
@Cacheable("disclaimerList")
public List<MyObjectDTO> getList(){
return apiClient.getListFromDb(); \\gets the list and stores in cache
}
MenuHelper(使用@Component 注释)这是检索缓存的位置
@Autowired
MenuService menuService;
@Autowired
CacheManager cacheManager;
private static MenuService menuServiceImpl;
private static CacheManager cacheManagerService;
@PostConstruct
void init(){
\\initializing variables here
MenuHelper.menuServiceImpl = menuService;
MenuHelper.cacheManagerService = cacheManager;
}
MenuHelper() {}
private static List<MyObjectDTO> getCacheList(){
if(cacheManager == null){
menuService.getList(); \\stores the cache; Null pointer exception occurs here!!
}
Cache cache = cacheManager.get("MyList"); \\getting the cache
Object obj = cache.get(SimpleKey.EMPTY).get(); \\getting cache stored with "EMPTY" key
List<MyObjectDTO> returnList = modelMapper.map(obj, new TypeToken<List<MyObjectDTO>>(){}.getType()); \\mapping it to a List of MyObjectDTO
return returnList;
}
什么时候menuHelper.getCacheList()在上面被调用,它会抛出一个空指针异常,其中menuService.getCache()正在被调用。我猜这是因为 menuService 没有自动装配。我已经在 @PostConstruct 方法中设置了值,但它不起作用。帮助/指导/指针将不胜感激!
【问题讨论】:
-
getCacheList()这是一个static方法。代码是否使用menuService作为实例变量进行编译?何时调用menuHelper.getCacheList()? -
它确实可以编译,但是当 menuHelper.getCacheList() 被调用时,它会抛出一个空指针异常。
-
您可以从名为
menuHelper.getCacheList()的位置添加样本吗? -
我不确定是否可以在静态字段中自动装配 bean。请问你为什么需要它们是静态的?
-
尝试在方法
getCacheList的开头声明MenuHelper.menuServiceImpl = menuService;并在此行放置一个断点...查看它在处理时是否为空。
标签: java spring spring-boot caching