一、前言
- Java注解的属性值,必须为 常量
- 有些场景想把 枚举名称 设置为 注解的属性值(如 spring-cache 用枚举配置缓存,使用时 需要 缓存名称)
二、方案
- 方案一:名称属性 + 外部名称接口
1@lombok.Getter 2@lombok.AllArgsConstructor 3public enum CommonCacheConfig { 4 QUOTE_LEVEL(CommonCacheConstant.QUOTE_LEVEL, 2); 5 6 private final String name; 7 8 private final int ttl; 9}
1public interface CommonCacheConstant { 2 3 String QUOTE_LEVEL = "QUOTE_LEVEL"; 4 5}
使用:@Cacheable(cacheNames = CommonCacheConstant.QUOTE_LEVEL)
- 方案二:名称属性 + 内部名称接口
1public enum CommonCacheConfig { 2 QUOTE_LEVEL(Constant.QUOTE_LEVEL, 2); 3 4 private final String name; 5 private final Integer ttl; 6 7 public interface Constant { 8 String QUOTE_LEVEL = "QUOTE_LEVEL"; 9 } 10}
使用:@Cacheable(cacheNames = CommonCacheConfig.Constant.QUOTE_LEVEL)
- 方案三:Lombok 的 FieldNameConstants
1@lombok.Getter 2@lombok.AllArgsConstructor 3@lombok.experimental.FieldNameConstants(onlyExplicitlyIncluded = true) 4public enum CommonCacheConfig { 5 6 @FieldNameConstants.Include QUOTE_LEVEL(2); 7 8 private final Integer ttl; 9 10}
使用:@Cacheable(cacheNames = CommonCacheConfig.Fields.QUOTE_LEVEL)
注意:FieldNameConstants 的 onlyExplicitlyIncluded 需设置为 true,否则 按枚举的属性(如 ttl)生成,同时在 枚举项前加 @FieldNameConstants.Include
三、总结
- 通过 Lombok 的 FieldNameConstants 自动生成 枚举名称常量,提高了 可维护性
- 参考:java - Use Enum type as a value parameter for @RolesAllowed-Annotation - Stack Overflow
本文首先发布于 https://www.890808.xyz/ ,其他平台需要审核更新慢一些。

