SyntaxHighlighter

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;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

public class BeanFactoryWrapper implements BeanFactoryAware {

 private org.springframework.beans.factory.support.DefaultListableBeanFactory 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.integration.channel.DirectChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/META-INF/spring/*-context.xml"})
public class ContextIntegrationTest {

 @Autowired
 @Qualifier("input.channel")
 private DirectChannel channel;
 
 @Autowired
 private ASomeService aSomeService;
 
 @Test
 public void test() throws Exception {
  assertNull(aSomeService.getPayload());
  //create a message with the header
  Message instruction = MessageBuilder.withPayload("hello world").setHeader("serviceName", "aSomeService").build();
  //send
  channel.send(instruction);
  //wait
  Thread.sleep(100);
  //now check 
  assertNotNull(aSomeService.getPayload());
 }
 
}

No comments:

Post a Comment