如何在编译期获取Maven provided scope依赖中的资源?
Maven provided依赖编译期资源获取问题解决思路
核心原因
Maven中provided scope的依赖仅在编译阶段提供类文件供代码编译,但不会将其包含的资源(如JSON文件)复制到项目的输出目录,也不会让这些资源进入编译期的有效classpath,导致常规资源加载方式无法访问。
可行解决方法
临时调整依赖Scope
开发编译阶段可临时将provided改为compile,待编译完成后改回原配置。此方法简单但易误操作,仅适合临时调试。使用Maven插件复制资源(推荐)
通过maven-dependency-plugin在编译前将provided依赖中的指定资源复制到项目target/classes目录,让编译期能正常加载。示例配置:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-provided-resources</id> <phase>process-resources</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <includeGroupIds>你的依赖groupId</includeGroupIds> <includeArtifactIds>你的依赖artifactId</includeArtifactIds> <includeScope>provided</includeScope> <outputDirectory>${project.build.directory}/classes</outputDirectory> <includes>**/*.json</includes> <!-- 按需指定资源匹配规则 --> </configuration> </execution> </executions> </plugin>注解处理器中直接读取Jar资源
在注解处理器逻辑中,通过依赖类的Class对象直接读取Jar内的资源,无需复制。示例代码:// 依赖中的基准类,用于定位Jar包 TypeElement targetElement = processingEnv.getElementUtils().getTypeElement("com.your.dep.TargetClass"); InputStream jsonStream = targetElement.getClass().getResourceAsStream("/name.json"); // 后续处理输入流
内容的提问来源于stack exchange,提问作者Victoria Viking
相关产品推荐
相关产品推荐

