一、前言
- Java注解的属性值,必须为 常量
- 有些场景想把 枚举名称 设置为 注解的属性值(如 spring-cache 用枚举配置缓存,应用时 须要 缓存名称)
二、计划
计划一:名称属性 + 内部名称接口
@lombok.Getter@lombok.AllArgsConstructorpublic enum CommonCacheConfig { QUOTE_LEVEL(CommonCacheConstant.QUOTE_LEVEL, 2); private final String name; private final int ttl;}
public interface CommonCacheConstant { String QUOTE_LEVEL = "QUOTE_LEVEL";}
应用:@Cacheable(cacheNames = CommonCacheConstant.QUOTE_LEVEL)
计划二:名称属性 + 外部名称接口
public enum CommonCacheConfig { QUOTE_LEVEL(Constant.QUOTE_LEVEL, 2); private final String name; private final Integer ttl; public interface Constant { String QUOTE_LEVEL = "QUOTE_LEVEL"; }}
应用:@Cacheable(cacheNames = CommonCacheConfig.Constant.QUOTE_LEVEL)
计划三:Lombok 的 FieldNameConstants
@lombok.Getter@lombok.AllArgsConstructor@lombok.experimental.FieldNameConstants(onlyExplicitlyIncluded = true)public enum CommonCacheConfig { @FieldNameConstants.Include QUOTE_LEVEL(2); private final Integer ttl;}
应用:@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/ ,其余平台须要审核更新慢一些。