sjvoon97
sjvoon97

Reputation: 23

Can I use enum in @Cacheable

I would like to use enum in a @Cacheable as its cache name such as @Cacheable(CacheName.CACHE_A.getName())

I have a sample enum like

public enum CacheName {
  CACHE_A("CACHE_A");
  private final String name;
  CacheName(String name){
    this.name=name;
  }
  public String getName(){
    return name;
  }
}

I tried to use it like a constant String as cache name in my service method

@Cacheable(CacheName.CACHE_A.getName())
public MyObject getObject(){ 
//return something 
}

This is not working.

It works when I declare a constant class with public static String CACHE_A = "CACHE_A";

Is there any workaround if I prefer to use enum over a constant class, I do not see any difference as enum suppose to be fixed, right? please correct me, thanks

Upvotes: 2

Views: 944

Answers (2)

Zahid Khan
Zahid Khan

Reputation: 3277

public enum CacheName {
    CACHE_A(Names.CACHE_A);

    public class Names{
        public static final String CACHE_A = "CACHE_A";
    }

    private final String label;

    private CacheName(String label) {
        this.label = label;
    }

    public String toString() {
        return this.label;
    }
}

And in annotation you can use it like

@Cacheable(CacheName.Names.CACHE_A)
public MyObject getObject(){ .. }

Upvotes: 1

Reveson
Reveson

Reputation: 809

If you don't mind using lombok then there is a neat trick to achieve that:

@FieldNameConstants(onlyExplicitlyIncluded = true)
public enum CacheName {
    @FieldNameConstants.Include CACHE_A,
}

and then in your annotation you have access to a static field throught Fields subclass:

@Cacheable(CacheName.Fields.CACHE_A)
public MyObject getObject(){
    //return something 
}

Tested on lombok version 1.18.28.

Upvotes: 5

Related Questions