第 5 章 Camel Quarkus 中的上下文和依赖注入(CDI)
CDI 在 Quarkus 和 Camel Quarkus 中扮演一个中央角色,为它提供第一个类支持。
您可以使用 @Inject、@ConfigProperty 和类似注解 e.g 将 Bean 和配置值注入 Camel RouteBuilder,例如:
import javax.enterprise.context.ApplicationScoped;
import javax.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
@Inject和@ConfigProperty需要@ApplicationScoped注释才能在RouteBuilder中工作。请注意,@ApplicationScopedBean 由 CDI 容器及其生命周期进行管理,因此比纯RouteBuilder中的一个复杂一些。换句话说,在RouteBuilder中使用@ApplicationScopedin some boot time penalty,因此您应该仅在真正需要时,将RouteBuilder标注为@ApplicationScoped。- 2
timer.period属性的值在 example 项目的src/main/resources/application.properties中定义。
提示
有关更多详细信息,请参阅 Quarkus 依赖注入指南。
5.1. 访问 CamelContext 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
访问 CamelContext 仅将其注入an:
import javax.inject.Inject;
import javax.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());
}
}