如何自定义一个条件注解让 Shiro 在指定 classpath 下才生效?

解读

这道题考察的是“让 Shiro 按需加载”的能力,国内大厂在微服务、多环境(sit/uat/prod)下经常要求“框架级组件可插拔”,避免把安全能力硬编码到业务包。
面试官真正想听的是:

  1. 你能否用 Spring Boot 的 @ConditionalOnClass 机制,把 Shiro 的初始化做成“有指定类才装配”;
  2. 你能否把条件再封装成业务语义清晰的自定义注解,而不是直接写 @ConditionalOnClass;
  3. 你能否保证顺序安全:条件注解要在 Shiro 自动配置类之前生效,防止提前触发静态代码块或创建 Filter 链。

知识点

  1. Spring Boot 条件装配:
    • @ConditionalOnClass / @ConditionalOnMissingClass
    • @Conditional 元注解与 Condition 接口
  2. 自定义组合注解:用 @AliasFor 做属性别名,保持与 Spring Boot 风格一致
  3. Shiro 自动配置顺序:
    • @AutoConfigureBefore / @AutoConfigureAfter
    • spring.factories(Spring Boot 2.7-)或 spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(Spring Boot 3+)
  4. 国内灰度发布场景:
    • 多环境 jar 包差异大,常用 apollo/naea 做开关,但 classpath 判断是最轻量、无网络依赖的方案

答案

  1. 定义条件注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(ShiroEnabledCondition.class)
public @interface ConditionalOnShiroEnabled {
    /**
     * 用来指定“当哪个类存在于 classpath 时才生效”,默认 Shiro 核心类
     */
    Class<?> value() default org.apache.shiro.mgt.SecurityManager.class;
}
  1. 写条件判断逻辑
public class ShiroEnabledCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attrs = metadata.getAnnotationAttributes(
                ConditionalOnShiroEnabled.class.getName());
        if (attrs == null || attrs.get("value") == null) {
            return false;
        }
        String className = ((Class<?>) attrs.get("value")).getName();
        return ClassUtils.isPresent(className, context.getClassLoader());
    }
}
  1. 在 Shiro 自动配置类上引用
@Configuration
@ConditionalOnShiroEnabled(value = com.mycompany.shiro.extension.ShiroRedissonAdapter.class)
@AutoConfigureBefore(name = "org.apache.shiro.spring.boot.autoconfigure.ShiroBeanAutoConfiguration")
public class MyShiroAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public SecurityManager securityManager(List<Realm> realms) {
        DefaultSecurityManager manager = new DefaultSecurityManager();
        manager.setRealms(realms);
        return manager;
    }
}
  1. 注册到 spring.factories(以 Spring Boot 2.7 为例)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mycompany.shiro.autoconfigure.MyShiroAutoConfiguration
  1. 打包验证
  • 在 sit 环境引入 shiro-redisson-adapter.jar,MyShiroAutoConfiguration 自动生效;
  • 在 prod 环境去掉该 jar,Shiro 整层自动回退,应用仍可启动,无 ClassNotFoundException。

拓展思考

  1. 如果条件类在运行时动态下载(比如通过 arthas 热补丁),Spring 的 Condition 只会执行一次,必须配合 Spring Cloud 的 @RefreshScope 或自定义 EnvironmentPostProcessor 重新触发条件判断。
  2. 国内银行项目常把 Shiro 的会话存储切换到 国密 SM4 加密,此时条件注解可扩展为:
    @ConditionalOnShiroEnabled(value = SM4SessionDAO.class, env = "prod")
    通过 Environment 读取 spring.profiles.active,实现“指定环境 + 指定类”双重判断。
  3. 在 Spring Boot 3 原生镜像 中,条件类会被 GraalVM 提前解析,务必把条件判断用到的类加入 --hint-class-initialization,否则编译期就被剔除,导致注解失效。