一、前言
- Java注解的屬性值,必須為 常量
- 有些場(chǎng)景想把 枚舉名稱(chēng) 設(shè)置為 注解的屬性值(如 spring-cache 用枚舉配置緩存,使用時(shí) 需要 緩存名稱(chēng))
二、方案
- 方案一:名稱(chēng)屬性 + 外部名稱(chēng)接口
@lombok.Getter
@lombok.AllArgsConstructor
public 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)
- 方案二:名稱(chēng)屬性 + 內(nèi)部名稱(chēng)接口
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 需設(shè)置為 true,否則 按枚舉的屬性(如 ttl)生成,同時(shí)在 枚舉項(xiàng)前加 @FieldNameConstants.Include
三、總結(jié)
- 通過(guò) Lombok 的 FieldNameConstants 自動(dòng)生成 枚舉名稱(chēng)常量,提高了 可維護(hù)性
- 參考:java - Use Enum type as a value parameter for @RolesAllowed-Annotation - Stack Overflow