@Profile Camel中的Spring注释

时间:2017-10-19 17:08:59

标签: spring-boot apache-camel spring-annotations

我有一个Spring Boot + Apache Camel项目非常出色。我刚刚添加了一个新的bean,但我希望它的实现是特定于配置文件的。我创建了Spring测试来验证它,并且它按预期工作,但是当我运行服务器时,我得到以下堆栈跟踪:

Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: MyFancyBean
    at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:94)
    at org.apache.camel.model.language.MethodCallExpression.createExpression(MethodCallExpression.java:196)
    at org.apache.camel.model.language.MethodCallExpression.createPredicate(MethodCallExpression.java:210)
    at org.apache.camel.model.language.ExpressionDefinition.createPredicate(ExpressionDefinition.java:148)
    at org.apache.camel.model.ValidateDefinition.createProcessor(ValidateDefinition.java:63)
    at org.apache.camel.model.ValidateDefinition.createProcessor(ValidateDefinition.java:35)
    at org.apache.camel.model.ProcessorDefinition.makeProcessorImpl(ProcessorDefinition.java:545)
    at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:506)
    at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:222)
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1068)

我有一个界面和两个实现:

public interface MyFancyBean { ... }

public class FooFancyBean implements MyFancyBean { ... }

public class NonFooFancyBean implements MyFancyBean { ... }

根据配置文件,读取实例化的正确bean:

@Configuration
public class AppConfig {
    @Bean
    @Profile("foo")
    MyFancyBean fooBean() {
        return new FooFancyBean();
    }

    @Bean
    @Profile("!foo")
    MyFancyBean nonFooBean() {
        return new NonFooFancyBean();
    }
}

我已经验证了这种方法有两种作用。首先,几个测试:

@ActiveProfiles("anything-but-foo")
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackages = {"com.example", "com.jtv.spring.boot"})
@EnableAutoConfiguration
@Component
public class NonFooBean_SpringTest {

    @Autowired
    private MyFancyBean bean;

    @Test
    // ... here "bean" is instantiated as "NonFooFancyBean"

所以测试工作正常。

此外,当我启动我的应用程序时,根据配置文件调用上面@Configuration类中的正确bean。

Camel 仍然生气并在启动时说“NoSuchBeanException”。

FWIW,这是我引用bean的方式:

@Component
public class MyCamelRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        // [...]
        from("direct:processStuff").
        validate().method("MyFancyBean").
        process("MyProcessor");
    }


}

如何让Camel尊重此配置?

1 个答案:

答案 0 :(得分:1)

Whoooo ...你们今天都要成为我的rubber duck。我只是自动装配了它。 (这对我的处理器不起作用,这就是我最初没有想到的原因。)

@Component
public class MyCamelRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        // [...]
        @Autowired MyFancyBean myFancyBean;

        from("direct:processStuff").
        validate().method(myFancyBean).
        process("MyProcessor");
    }
}