You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在现有Spring Boot项目中集成JMH遇「无匹配基准测试」问题求助

解决Spring Boot项目中JMH "No matching benchmarks" 错误

1. 修正依赖Scope与编译配置

JMH依赖需限定在test作用域,且必须确保注解处理器在测试编译阶段生效。修改Maven依赖配置:

<dependencies>
    <dependency>
        <groupId>org.openjdk.jmh</groupId>
        <artifactId>jmh-core</artifactId>
        <version>1.35</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.openjdk.jmh</groupId>
        <artifactId>jmh-generator-annprocess</artifactId>
        <version>1.35</version>
        <scope>test</scope>
        <optional>true</optional>
    </dependency>
</dependencies>

同时配置Maven编译插件,确保测试阶段启用注解处理:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.11.0</version>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.openjdk.jmh</groupId>
                        <artifactId>jmh-generator-annprocess</artifactId>
                        <version>1.35</version>
                    </path>
                </annotationProcessorPaths>
                <testAnnotationProcessorPaths>
                    <path>
                        <groupId>org.openjdk.jmh</groupId>
                        <artifactId>jmh-generator-annprocess</artifactId>
                        <version>1.35</version>
                    </path>
                </testAnnotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

2. 规范基准测试类

  • 确保TestBenchmark类放在具体包路径下(不要用默认包),比如com.yourproject.benchmark
  • 可补充注解明确基准测试行为,避免空实现被忽略:
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;

public class TestBenchmark {
    @Benchmark
    @OutputTimeUnit(TimeUnit.MILLISECONDS)
    public void init() {
        // 空实现也会被JMH识别,前提是注解处理器生效
    }
}

3. 精准运行基准测试

方式一:指定基准类运行

修改BenchmarkRunner,直接传入基准类的全限定名,避免JMH扫描遗漏:

public class BenchmarkRunner {
    public static void main(String[] args) throws Exception {
        // 替换为你的TestBenchmark全限定类名
        org.openjdk.jmh.Main.main(new String[]{"com.yourproject.benchmark.TestBenchmark"});
    }
}

方式二:IDE插件配置

使用IntelliJ的JMH插件时,需:

  • 选择项目的test模块作为运行目标
  • 勾选"Include test sources"选项

4. 清理重编译确保生成代理类

执行Maven命令清理旧编译文件,重新编译测试代码,保证JMH生成的代理类被正确创建:

mvn clean test-compile

5. 规避Spring Boot自动配置干扰

若以上步骤无效,将基准测试类放在src/test/java下独立的包中,且不要添加@SpringBootTest等Spring测试注解(若需测试Spring Bean,需额外配置JMH与Spring的集成逻辑)。


内容的提问来源于stack exchange,提问作者Ed .d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:55:21