注册表
org.apache.camel.spi.Registry
API 是一个通用的 API,用于在任何类型的运行时平台上查找 bean,无论您是在 Spring Boot、Quarkus、独立运行、Kafka 还是其他平台上运行 Camel。
骆驼使用基于运行时平台(如 Spring Boot、Quarkus 等)的 DefaultRegistry
,首先从运行时平台查找 bean,然后回退到骆驼自己的 SimpleRegistry
。
注册表 API
注册表有两套 API:
-
绑定
-
查找
绑定 API 用于将新的 bean 添加到注册表中。查找用于从注册表中查找现有的 bean。
绑定 API
绑定 API 如下:
public interface Registry extends BeanRepository {
/**
* Binds the bean to the repository (if possible).
* If the bean is CamelContextAware then the registry will automatic inject the context if possible.
*
* @param id the id of the bean
* @param bean the bean
*/
void bind(String id, Object bean);
/**
* Binds the bean to the repository (if possible).
* Binding by id and type allows to bind multiple entries with the same id but with different type.
* If the bean is CamelContextAware then the registry will automatic inject the context if possible.
*
* @param id the id of the bean
* @param type the type of the bean to associate the binding
* @param bean the bean
*/
void bind(String id, Class<?> type, Object bean);
}
如果你需要将一个 bean 添加到 Registry
中,你可以通过以下方式轻松地在 Java 中实现:
Object myFoo = ...
camelContext.getRegistry().bind("foo", myFoo);
然后您可以通过 id 访问 bean,例如从 Camel 路由中:
from("jms:cheese").bean("foo");
在 Spring XML 中绑定
如果您使用 Spring XML 文件,那么任何 <bean>
都会由 Spring 自动处理,并注册到 Spring bean 容器中;这意味着不需要从 Camel 中绑定 bean。
<bean id="foo" class="com.foo.MyFoo"/>
查找 API
注册表主要用于通过 ID 或类型查找 bean。在 Camel 启动期间,Camel 会将所有组件、端点、路由、处理器和 bean 等进行连接,这时会大量使用注册表。
查找 API 包括以下方法:
public interface BeanRepository {
/**
* Looks up a bean in the registry based purely on name, returning the bean or null if it could not be found.
*
* Important: Multiple beans of different types may be bound with the same name, and its encouraged to use the
* lookupByNameAndType(String, Class) to lookup the bean with a specific type, or to use any of the
* find methods.
*
* @param name the name of the bean
* @return the bean from the registry or null if it could not be found
*/
Object lookupByName(String name);
/**
* Looks up a bean in the registry, returning the bean or null if it could not be found.
*
* @param name the name of the bean
* @param type the type of the required bean
* @return the bean from the registry or null if it could not be found
*/
<T> T lookupByNameAndType(String name, Class<T> type);
/**
* Finds beans in the registry by their type.
*
* @param type the type of the beans
* @return the types found, with their bean ids as the key. Returns an empty Map if none found.
*/
<T> Map<String, T> findByTypeWithName(Class<T> type);
/**
* Finds beans in the registry by their type.
*
* @param type the type of the beans
* @return the types found. Returns an empty Set if none found.
*/
<T> Set<T> findByType(Class<T> type);
}
您可以按照以下示例从 Java 代码中查找 bean
// lookup by id only
Object foo = camelContext.getRegistry().lookupByName("foo");
// lookup by type so there is no need for type casting
MyFoo foo2 = camelContext.getRegistry().lookupByNameAndType("foo", MyFoo.class);