第 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 1 public class TimerRoute extends RouteBuilder { @ConfigProperty(name = "timer.period", defaultValue = "1000") 2 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
中工作。请注意,@ApplicationScoped
Bean 由 CDI 容器管理,其生命周期比其中一个纯文本RouteBuilder
更复杂。换句话说,在RouteBuilder
中使用@ApplicationScoped
RouteBuilder
标注。- 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()); } }