Thursday, May 30, 2013

Spring Integration - Calling a Service based on a Header Value

Spring Integration - Calling a Service based on a Header Value

here's a situation you may have encountered in Spring Integration, based on a header value, you want to invoke a certain service.  but, you've got a whole bunch of the services and putting in a header value router with an endpoint for each one is a bit of a pain, especially if they all inherit from the same Interface.

so, here's a quick solution to simplify your Spring Integration configuration;

here's the XML,




here's our wrapper bean - it's responsible for exposing the BeanFactory

package de.incompleteco.spring.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class BeanFactoryWrapper implements BeanFactoryAware {

 private beanFactory;
 public Object getBean(String name) throws BeansException {
  return beanFactory.getBean(name);

 public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  this.beanFactory = (DefaultListableBeanFactory) beanFactory;


and finally, a simple test to see if it works

package de.incompleteco.spring.integration;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.Message;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import de.incompleteco.spring.integration.service.ASomeService;

public class ContextIntegrationTest {

 private DirectChannel channel;
 private ASomeService aSomeService;
 public void test() throws Exception {
  //create a message with the header
  Message instruction = MessageBuilder.withPayload("hello world").setHeader("serviceName", "aSomeService").build();
  //now check 

No comments:

Post a Comment