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

Spring Boot Camel项目测试问题:@EndpointInject注入均为null但@Autowired可正常工作

解决Spring Boot 2.5.1 + Apache Camel 3.10.0测试中@EndpointInject/@Produce注解不生效的问题

我之前在Camel 3.x搭配Spring Boot 2.5.x的项目里也遇到过完全一样的问题——Spring原生的@Autowired能正常工作,但Camel的专属注解就是死活不生效。结合官方文档和实际踩坑经验,你可以尝试以下几个解决方案:

1. 先确认引入了正确的测试依赖

首先检查你的pom.xml(Maven)或build.gradle(Gradle),确保引入了Camel Spring Boot的测试 starter,而不是普通的Camel测试依赖:

Maven示例:

<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-spring-boot-starter-test</artifactId>
    <version>3.10.0</version>
    <scope>test</scope>
</dependency>

这个依赖包含了处理Camel专属注解的AutowiredAnnotationBeanPostProcessor等核心类,是注解生效的基础。

2. 给@CamelSpringBootTest指定Spring Boot主类

你的测试类当前只加了@CamelSpringBootTest,但如果测试类和Spring Boot主类不在同一个包下,Spring Boot无法自动扫描到应用的配置,导致Camel的自动配置没有被加载。

修改测试类,指定你的Spring Boot主类:

@CamelSpringBootTest(classes = YourApplicationMainClass.class) // 替换成你的主类
class UnmarshalXmlTest {
    @EndpointInject("mock:out")
    MockEndpoint outEndpoint;
    
    @Produce("direct:in")
    ProducerTemplate template;

    @Test
    void test() {
        assertNotNull(outEndpoint);
        assertNotNull(template);
    }
}

如果测试类和主类在同一个包下,这个属性可以省略,但显式指定能避免很多扫描问题。

3. (可选)为测试定义专属的路由配置

如果你不想加载整个应用上下文,只想测试特定路由,可以在测试类内部定义一个测试用的配置类,确保Camel上下文和路由被正确初始化:

@CamelSpringBootTest
class UnmarshalXmlTest {
    @EndpointInject("mock:out")
    MockEndpoint outEndpoint;
    
    @Produce("direct:in")
    ProducerTemplate template;

    @Configuration
    static class TestRouteConfig {
        @Bean
        public RouteBuilder testRoute() {
            return new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    // 定义测试用的路由,和你的业务路由对应
                    from("direct:in")
                        .to("mock:out");
                }
            };
        }
    }

    @Test
    void test() {
        assertNotNull(outEndpoint);
        assertNotNull(template);
    }
}

这种方式会只加载测试所需的最小上下文,同时确保Camel的注解处理器被正确注册。

4. 验证注解处理器是否生效

如果以上步骤都试过还是不行,可以在测试里加一段调试代码,检查Camel的注解处理器是否存在:

@Autowired
private List<BeanPostProcessor> beanPostProcessors;

@Test
void checkCamelProcessor() {
    boolean hasCamelProcessor = beanPostProcessors.stream()
        .anyMatch(p -> p.getClass().getName().contains("AutowiredAnnotationBeanPostProcessor"));
    assertTrue("Camel注解处理器未注册", hasCamelProcessor);
}

如果返回false,说明你的依赖或配置有问题,需要重新检查依赖版本和测试类注解。

内容的提问来源于stack exchange,提问作者dermoritz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:48:11