Camel how to add something to registry - with java, in general

后端 未结 3 886
逝去的感伤
逝去的感伤 2020-12-20 16:39

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

3条回答
  •  旧时难觅i
    2020-12-20 16:53

    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.

提交回复
热议问题