第 5 章 Camel Quarkus 中的上下文和依赖注入(CDI)
CDI 在 Quarkus 中扮演了一个中央角色,而 Camel Quarkus 也为它提供了第一类支持。
您可以使用 @Inject、@ConfigProperty 和类似注解(例如,将 bean 和配置值注入 Camel RouteBuilder ),例如:
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.camel.builder.RouteBuilder;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@ApplicationScoped
public class TimerRoute extends RouteBuilder {
@ConfigProperty(name = "timer.period", defaultValue = "1000")
String period;
@Inject
Counter counter;
@Override
public void configure() throws Exception {
fromF("timer:foo?period=%s", period)
.setBody(exchange -> "Incremented the counter: " + counter.increment())
.to("log:cdi-example?showExchangePattern=false&showBodyType=false");
}
}
- 1
@ApplicationScoped注释需要@Inject和@ConfigProperty,才能在RouteBuilder中工作。请注意,@ApplicationScopedBean 由 CDI 容器管理,其生命周期比其中一个纯文本RouteBuilder更复杂。换句话说,在RouteBuilder中使用会有一些引导时间损失,因此,您应该仅在需要时为@ApplicationScopedRouteBuilder标注。- 2
timer.period属性的值在 example 项目的src/main/resources/application.properties中定义。
提示
如需了解更多详细信息,请参阅 Quarkus Dependency Injection 指南。
5.1. 访问 CamelContext 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
要访问 CamelContext,只需将其注入您的 bean:
import jakarta.inject.Inject;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.stream.Collectors;
import java.util.List;
import org.apache.camel.CamelContext;
@ApplicationScoped
public class MyBean {
@Inject
CamelContext context;
public List<String> listRouteIds() {
return context.getRoutes().stream().map(Route::getId).sorted().collect(Collectors.toList());
}
}