이 콘텐츠는 선택한 언어로 제공되지 않습니다.
Chapter 5. Contexts and Dependency Injection (CDI) in Camel Quarkus
CDI plays a central role in Quarkus and Camel Quarkus offers a first class support for it too.
You may use @Inject, @ConfigProperty and similar annotations e.g. to inject beans and configuration values to your Camel RouteBuilder, for example:
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
- The
@ApplicationScopedannotation is required for@Injectand@ConfigPropertyto work in aRouteBuilder. Note that the@ApplicationScopedbeans are managed by the CDI container and their life cycle is thus a bit more complex than the one of the plainRouteBuilder. In other words, using@ApplicationScopedinRouteBuildercomes with some boot time penalty and you should therefore only annotate yourRouteBuilderwith@ApplicationScopedwhen you really need it. - 2
- The value for the
timer.periodproperty is defined insrc/main/resources/application.propertiesof the example project.
Please refer to the Quarkus Dependency Injection guide for more details.
5.1. Accessing CamelContext 링크 복사링크가 클립보드에 복사되었습니다!
To access CamelContext just inject it into your bean:
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());
}
}
5.2. CDI and the Camel Bean component 링크 복사링크가 클립보드에 복사되었습니다!
5.2.1. Refer to a bean by name 링크 복사링크가 클립보드에 복사되었습니다!
To refer to a bean in a route definition by name, just annotate the bean with @Named("myNamedBean") and @ApplicationScoped. The @RegisterForReflection annotation is important for the native mode.
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import io.quarkus.runtime.annotations.RegisterForReflection;
@ApplicationScoped
@Named("myNamedBean")
@RegisterForReflection
public class NamedBean {
public String hello(String name) {
return "Hello " + name + " from the NamedBean";
}
}
Then you can use the myNamedBean name in a route definition:
import org.apache.camel.builder.RouteBuilder;
public class CamelRoute extends RouteBuilder {
@Override
public void configure() {
from("direct:named")
.to("bean:namedBean?method=hello");
}
}