sometimes I have to add an object to camel registry (of course with java). In most cases it is a dataSource .
My problem is I can\'t figure out a general working way
If you're using the camel-spring
package, you can use Spring to manage the registry. Here's an example of code I used to add a singleton bean in Java through Spring:
MyApplicationContext.xml
MyApplication.java
public class MyApplication {
public static void main(final String[] args) {
final FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("/path/to/MyApplicationContext.xml");
}
}
MyRouteBuilder.java
public void MyRouteBuilder extends RouteBuilder implements ApplicationContextAware {
@Override
public void configure() {
from("ftps://localhost:21/foo?pollStrategy=#myPollingStrategy")
.log("${body}");
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
final ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;
final DefaultListableBeanFactory registry = (DefaultListableBeanFactory)context.getBeanFactory();
registry.registerSingleton("myPollingStrategy", new MyPollingStrategy());
}
}
The important part here is to implement the ApplicationContextAware
interface in the class that you want to use to manually add beans to the registry. This interface can be implemented on any bean that Spring initializes; you don't have to use your RouteBuilder. In this case, the bean is created on startup during the setApplicationContext(...)
execution before configure()
is called, but you can also store the application context for use later (which is probably a more common usage).
This was tested with Camel 2.19.0
and Spring 4.3.10-RELEASE
.