如何把 ini 文件编译为配置类消除运行时解析?

解读

国内互联网面试中,“消除运行时解析” 本质上是考察你对 Shiro 启动性能、云原生镜像体积、以及 Spring Boot 原生编译(GraalVM Native Image) 的落地经验。
HR 常追问:

  1. 为什么 ini 在微服务里被嫌弃?——运行时 IO + 反射解析导致启动慢、内存高、AOT 不支持。
  2. 怎么证明你改造后真的“零解析”?——编译期生成 Java 配置类,打包后 classpath 里再无 .ini,Native Image 无需 Resources 配置。
    因此,回答必须给出**“可落地的编译期代码生成方案”**,而不是简单地把 ini 内容硬编码到 @Bean 方法里。

知识点

  1. Shiro 配置加载链:IniSecurityManagerFactory → Ini → Ini.Section → ReflectionBuilder,全程发生在运行时。
  2. Spring Boot 3.x AOT / GraalVM Native Image 要求所有反射、资源、动态代理必须在编译期确定;ini 文件被归类为“资源文件”,默认要额外配置 -H:IncludeResources,且解析用的反射字段无法自动推断。
  3. Java Annotation Processor(APT) 能在编译期扫描 src/main/resources/shiro.ini,生成一个带 @ConfigurationProperties 的 Java 类,彻底抹掉 ini 文件。
  4. Shiro 官方提供的 DefaultWebSecurityManager 所有属性(realm、sessionManager、cacheManager、密码匹配器)均可通过 setter 注入,无需再走 Ini 反射路径。
  5. Maven 生命周期:process-resources → compile → apt 生成代码 → 后续打包插件(spring-boot-maven-plugin 或 native-maven-plugin)不再感知 ini 存在。

答案

步骤一:定义 APT 注解

@SupportedAnnotationTypes("com.xxx.shiro.GenerateShiroConfig")
@SupportedSourceVersion(SourceVersion.RELEASE_17)
public class ShiroConfigProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        // 1. 编译期读取 shiro.ini
        InputStream in = processingEnv.getFiler()
                            .getResource(StandardLocation.CLASS_OUTPUT, "", "shiro.ini").openInputStream();
        Ini ini = new Ini();
        ini.load(in);

        // 2. 生成配置类源码文本
        String className = "CompiledShiroConfig";
        StringBuilder sb = new StringBuilder();
        sb.append("package com.xxx.shiro.generated;\n");
        sb.append("@org.springframework.context.annotation.Configuration\n");
        sb.append("public class ").append(className).append(" {\n");

        // 3. 遍历 Ini.Section,生成 @Bean 方法
        ini.getSections().forEach((name, section) -> {
            if ("users".equals(name)) return;   // 用户写死到内存Realm
            sb.append("  @Bean\n");
            sb.append("  public ").append(section.get("class"))
              .append(" ").append(name).append("() {\n");
            sb.append("    ").append(section.get("class"))
              .append(" bean = new ").append(section.get("class")).append("();\n");
            section.forEach((k,v) -> {
                if ("class".equals(k)) return;
                sb.append("    bean.set").append(camel(k)).append("(").append(wrap(v)).append(");\n");
            });
            sb.append("    return bean;\n  }\n");
        });

        // 4. 生成 SecurityManager 汇总
        sb.append("  @Bean\n");
        sb.append("  public org.apache.shiro.web.mgt.DefaultWebSecurityManager securityManager() {\n");
        sb.append("    DefaultWebSecurityManager sm = new DefaultWebSecurityManager();\n");
        sb.append("    sm.setRealm(myRealm());\n");
        sb.append("    return sm;\n  }\n");
        sb.append("}\n");

        // 5. 写入 Java 文件
        JavaFileObject file = processingEnv.getFiler()
                               .createSourceFile("com.xxx.shiro.generated." + className);
        try (Writer w = file.openWriter()) {
            w.write(sb.toString());
        }
        return true;
    }
}

步骤二:在 pom.xml 注册 APT 插件

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <annotationProcessorPaths>
      <path>
        <groupId>com.xxx.shiro</groupId>
        <artifactId>shiro-apt</artifactId>
        <version>1.0.0</version>
      </path>
    </annotationProcessorPaths>
  </configuration>
</plugin>

步骤三:删除 shiro.ini,编译后得到
target/generated-sources/annotations/com/xxx/shiro/generated/CompiledShiroConfig.java
该 Java 文件随 jar 一起发布,运行时直接走 Spring IoC,无任何 ini 解析逻辑。

步骤四:验证 Native Image
mvn -Pnative native:compile
native-image 不再提示“Resource not found: shiro.ini”,启动时间缩短 30% 以上,内存下降 10MB+。

拓展思考

  1. 多环境差异:国内公司常把 users、roles、perms 抽成 Apollo/Nacos 配置,APT 可扩展为“编译期生成占位符 + 运行期 @ConfigurationProperties 绑定”,既保留 AOT 优势,又支持动态权限。
  2. 兼容老系统:如果遗留 ini 里用了自定义过滤器,APT 需扫描 filters.* 段,动态生成 FilterRegistrationBean,避免手动维护 Java 配置。
  3. 灰度发布:把 APT 做成 Maven Profile,仅在生产打包时开启,日常开发仍用 ini,降低迁移阻力。
  4. 安全合规:编译期生成代码可自动做敏感词脱敏(如密码字段替换成外部 KMS 占位符),满足国内金融等保 2.0 要求。