Java 参数值为空时如何在@Cacheable中创建多个缓存键

Java 参数值为空时如何在@Cacheable中创建多个缓存键,java,spring-boot,caching,ehcache-3,Java,Spring Boot,Caching,Ehcache 3,我正在尝试创建具有多个参数值的缓存键 @Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id") private JSONObject getData(String name, String id) throws Exception { 在上述场景中,I name是必填字段,而id是可选字段。我想以这样的方式创建密钥: 如果name=“test”且id=null,则缓存键必须是cache\u name\u test 如果n

我正在尝试创建具有多个参数值的缓存键

@Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id")
private JSONObject getData(String name, String id) throws Exception {
在上述场景中,I name是必填字段,而id是可选字段。我想以这样的方式创建密钥:

  • 如果name=“test”且id=null,则缓存键必须是cache\u name\u test
  • 如果name=“test”和id=“2”,则缓存键必须是cache\u name\u test\u 2
  • 当前,如果未在参数值中传递id,则该键将形成类似“cache\u name\u test\u null”的内容

    是否可以使用@Cacheable注解创建这样的密钥?

    解决方案 这是可行的,但您需要在@Caching注释中包装2个@Cachable注释

    @Caching(
          cacheable = {
                @Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id", condition = "#id != null"),
                @Cacheable(cacheNames = "cache_name_", key = "#name", condition = "#id == null")
          }
        )
    public JSONObject getData(String name, String id) throws Exception {
    
    关于私有方法的说明
    您正在私有方法上使用@Caching注释。这不管用。这些注释仅适用于从类外部调用的公共方法。查看此堆栈溢出回答:

    这适用于公共方法,但条件#id!=根据官方的SPEL手册,null不起作用,这应该起作用。您可以添加您当前的代码吗?也许问题出在其他地方?我犯了一个错误,在条件中给出了错误的密钥名