实现自定义 @ConditionalOnFeatureFlag 注解并兼容 Spring Boot 3.2
解读
面试官抛出这道题,核心不是让你写个注解那么简单,而是考察你对 Spring Boot 3.2 条件装配机制、配置属性绑定、生命周期以及“国内灰度发布”场景的落地能力。
国内大厂(阿里、字节、美团)做热开关时,普遍要求:
- 配置可动态刷新(Nacos、Apollo),不能重启;
- 注解要支持SpEL 表达式(方便 AB 实验按 uid 尾号分流);
- 必须兼容 Spring Boot 3.2 的 AOT/Native 编译,不能出现反射警告。
如果候选人只给出静态@ConditionalOnProperty的改壳版本,直接会被判“初级”。
知识点
- Spring Boot 3.2 条件装配顶层接口:
Condition→@ConditionalOnFeatureFlag - 配置属性动态刷新:
@ConfigurationProperties+@RefreshScope(或 Spring CloudContextRefresher) - SpEL 解析器:
ExpressionParser与EvaluationContext的线程安全用法 - AOT 提示:
RuntimeHintsRegistrar注册反射/资源,防止 GraalVM 编译后丢失字段 - 国内灰度常见维度:用户尾号、城市编码、App 版本、渠道号,需支持多级回退策略
- Spring 3.2 新特性:
@ImportRuntimeHints替代spring.factories,务必掌握
答案
// 1. 定义注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(OnFeatureFlagCondition.class)
public @interface ConditionalOnFeatureFlag {
String key(); // 配置项,如 user.center.new
String expected() default "true"; // 期望值
String spel() default ""; // 可选 SpEL,优先级高于 key
}
// 2. 条件实现,兼容 Boot 3.2 AOT
class OnFeatureFlagCondition implements Condition {
private static final String HINTS = "OnFeatureFlagConditionHints";
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 读取注解属性
Map<String, Object> attrs = metadata.getAnnotationAttributes(ConditionalOnFeatureFlag.class.getName());
String key = (String) attrs.get("key");
String expected = (String) attrs.get("expected");
String spel = (String) attrs.get("spel");
// 动态配置源,优先走 Environment,再尝试 RefreshScope
Environment env = context.getEnvironment();
FeatureFlagService service = null;
try {
service = context.getBeanFactory().getBean(FeatureFlagService.class);
} catch (NoSuchBeanDefinitionException ignore) {
// 未接入动态刷新,降级到 Environment
}
boolean result;
if (StringUtils.hasText(spel)) {
// 构造 SpEL 上下文,把配置与当前登录用户放进去
StandardEvaluationContext spelContext = new StandardEvaluationContext();
spelContext.setBeanResolver(new BeanFactoryResolver(context.getBeanFactory()));
spelContext.setVariable("uid", RequestContextHolder.getRequestAttributes() == null ? 0L :
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
.getHeader("x-uid"));
ExpressionParser parser = new SpelExpressionParser();
result = Boolean.TRUE.equals(parser.parseExpression(spel).getValue(spelContext, Boolean.class));
} else {
String value = service != null ? service.getFlag(key) : env.getProperty(key, "false");
result = expected.equalsIgnoreCase(value);
}
return result;
}
}
// 3. 动态配置服务,对接 Nacos/Apollo
@Component
@ConfigurationProperties(prefix = "feature")
@RefreshScope
public class FeatureFlagService {
private Map<String, String> flag = new ConcurrentHashMap<>();
public String getFlag(String key) {
return flag.getOrDefault(key, "false");
}
public void setFlag(Map<String, String> flag) {
this.flag = flag;
}
}
// 4. AOT 提示,防止 GraalVM 编译丢失字段
@ImportRuntimeHints(OnFeatureFlagConditionRuntimeHints.class)
class OnFeatureFlagConditionRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerField(ConditionalOnFeatureFlag.class.getDeclaredField("key"));
hints.reflection().registerField(ConditionalOnFeatureFlag.class.getDeclaredField("expected"));
hints.reflection().registerField(ConditionalOnFeatureFlag.class.getDeclaredField("spel"));
}
}
// 5. 使用示例
@RestController
@ConditionalOnFeatureFlag(key = "user.center.new", expected = "true")
public class NewUserController {
@GetMapping("/api/v2/user")
public String home() {
return "new user center";
}
}
关键点:
- 条件类里绝不直接
@Autowired,用BeanFactory延迟拿,避免 AOT 提前实例化; - SpEL 上下文把 uid 注入,支持阿里常用尾号灰度
${uid % 100}; - 用
@ImportRuntimeHints代替已废弃的spring.factories,这是 Spring Boot 3.2 的硬性要求; - 如果公司用字节火山引擎做实验,可把
FeatureFlagService换成其 SDK,逻辑不变。
拓展思考
- 性能:每次条件都解析 SpEL 会压测失败,国内大厂会加本地缓存+Caffeine,过期时间 1s,保证热开关实时性同时 QPS 提升 10 倍。
- 安全:SpEL 必须白名单模式,禁止
T(java.lang.Runtime)等危险调用,可继承SimpleEvaluationContext并关闭类型引用。 - 多环境:结合 Spring Boot 3.2 的
spring.profiles.group,在application-gray.yml里默认开启灰度,上线单一键切换,无需改代码。 - 云原生:如果后续迁到 Kubernetes + Argo Rollout,可把注解扩展为
@ConditionalOnCanary(weight = 20),通过 Downward API 注入 Pod 标签,实现无配置中心的灰度,这是阿里云龙原生团队目前主推方案。