【问题标题】:Service giving null pointer in a Component服务在组件中提供空指针
【发布时间】: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


【解决方案1】:

我能够通过首先在调用 getCacheList() 方法的服务中自动装配 MenuHelper 来解决该错误。然后我调用init() 方法来初始化静态变量(非常重要的步骤)并从getCacheList() 方法中删除“静态”标识符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    相关资源
    最近更新 更多