,

In this post, I’m going to walk you through using Spring Boot to setup a Hello World example using Spring Integration and ActiveMQ. We’ll configure Spring Integration to listen on a ActiveMQ queue. For fun, I’ll use Spock to place a message on the queue, and we can watch Spring Integration receive the JMS Message and print a message to the console.

Spring Boot Project Setup

Spring Initializr

Using IntelliJ to create a new project, I’ll select the option to use the Spring Initializr to create my new Spring Boot project. The IntellIj dialog makes it easy to create a Spring Boot project.

In this case, I’m selecting the latest version of Spring Boot (1.3.0.M3) at the time of writing, and the option for Spring Integration.

IntelliJ and Spring Initializr

After completing the steps in IntelliJ, I’ll have a fresh Maven project to work with for this example.

Spring Integration and ActiveMQ Dependencies

Spring Boot does a pretty good job of bringing in the basic dependencies. Using the Maven support in IntelliJ, we can look at Maven dependencies for our project. You can see that via the Spring Boot artifacts, we’re bringing in the basic dependencies for Spring Integration.

Spring Boot and Spring Integration maven dependencies in IntelliJ

 

At the time of writing, the Spring Initializr does not support ActiveMQ directly. I didn’t look to see if the Spring Boot team defined a Maven artifact for this or not. But, it’s simple enough to add the dependencies we will need for Spring Integration and ActiveMQ.

Notice how I have not added version information to the dependencies? That gets inherited from the parent Spring Boot Maven POM.

ActiveMQ Spring Boot Configuration

Like many other things, Spring Boot makes our task of configuring ActiveMQ easier. For the purposes of our example, we want to use an embedded ActiveMQ broker. This is common to use when developing Spring projects which use ActiveMQ. Often when developing enterprise applications using Spring, you will use a ActiveMQ embedded broker for development  and then have a configuration to use IBM’s MQSeries in production.

ActiveMQ Broker

By just having ActiveMQ on our build path, Spring Boot will automatically set up a ActiveMQ broker. We need to set a couple properties to make it an in memory broker, without connection pooling. We can do this by setting two properties for Spring Boot.

application.properties

ActiveMQ Queue Configuration

We also need to setup a queue for our example. We can do this in a Spring Java Configuration class as follows.

ActiveMQConfig.java

This is all we need to do to configure ActiveMQ for our example. Spring Boot will take care of the rest.

Spring Integration Configuration

Spring Integration JMS Channel Adapter

Spring Integration comes with a number of different channel adapters. In this case, we need to configure a JMS channel adapter. This will serve as a transparent bridge between Spring Integration Messaging and JMS Messaging.

In the Spring Integration XML configuration below, I’ve defined a Spring Integration JMS channel adapter. The destination property is set to the name of the ActiveMQ queue bean we defined above. (When using Spring Java configuration, the bean reference becomes is inherited from the method name in the configuration class.) I’ve also added a Spring Integration channel to the configuration.

This acts as a bridge, messages coming from the JMS queue will get sent the the Spring Integration channel, and messages sent to the Spring Integration channel will get passed along to the JMS queue.

si-config.xml

Say Hello Service

We’ll use a simple service for our example today. Its a Spring Service component, which simply takes a string in and prints it out to the console.

SayHelloService.java

Spring Integration Service Activator Configuration

Next we need to add a Spring Integration Service Activator. This is what Spring Integration will use to process the message. We just need to add the following to our Spring Integration XML file.

/resources/spring/si-config.xml

Spring Boot Configuration

We need to tell Spring Boot about the Spring Integration XML configuration file. We can to this by adding an ImportResource  annotation to the Spring Boot application class file as follows.

HelloWorldSiActivemqApplication.class

Spock Configuration

Maven Dependencies

To enable Spock support add the following dependencies to your Maven pom file.

Maven Compiler Plugin

Spock test classes are written in Groovy. You will need to add a Groovy compiler to your Maven build. I like to use the Groovy Eclipse Compiler. Add the following plugin to your build plugins.

Sending a JMS Message Using Spock

There’s a lot of different ways to send a JMS message. I chose to use Spock for this example mostly for fun. I enjoy using Spock. In this example, I’ve setup Spock to use the same Spring context used by the Spring Boot Application. The Spring Boot Application class is actually a Spring Configuration class you can source into your Spring Integration tests.

Spock Spring Integration Test

In this Spock Integration test, using the Spring Boot configuration, I autowire in an instance of the JMS connection factory and setup a JMS producer to send a text message. This will drop a text message on the the same ActiveMQ JMS queue we configured Spring Integration to listen on.

SayHellowServiceJMSIT.groovy

Running the Spock Integration Test

Using IntelliJ, running the Spock integration test can simply be done by right clicking on the test method, and then clicking on ‘run’.

running a spock test in Intellij

 

Test Output

Spring Integration JMS Configuration for Spring Boot

Intentionally left an error in the Spring Integration configuration to demonstrate this error. The Spring Integration configuration be default is looking for a Spring Bean called ‘connectionFactory’. Spring Boot by default, creates the JMS connection factory using the name ‘jmsConnectionFactory’.

The solution is easy enough to implement. We just need to update the Spring Integration channel adapter to use the Spring Bean ‘jmsConnectionFactory’ instead of it’s default value of ‘connectionFactory.

si-config.xml

Running the Updated Configuration

When we run the Spock Integration Test again, we can see our expected hello world message in the console output.

Test Output

Conclusion

In this Spring Framework example, I’ve shown you how easy it is to use Spring Boot to configure an Active MQ broker for use with Spring Integration. This blog post was inspired by a real world example where I was coding a enterprise service using the Spring Framework. I needed to use Spring Integration to consume messages off of a MQSeries JMS queue. MQSeries is great, but its not very light weight, nor is it appropriate for Integration tests. Thus, I wrote my integration tests to use an embedded ActiveMQ broker. You can see how easy it was to use Spring Boot to provide the ActiveMQ broker, and dependency injection to wire everything up.

4
Share
, ,

Polyglot Programming

Is the practice of programming in multiple programming languages. According to Wikipedia it is –

In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.

In writing the code for a recent blog post on Spring Integration, I thought it would be fun to write some of the code in Groovy. I’ve been writing in Groovy for about 7 years. I’m as fluent in Groovy as I am in Java, so its no problem for me to bounce between the two languages. If you been following my blog, you’ve probably seen me use Spock for my unit tests. Spock is a great tool. A Groovy testing framework for testing Java code.

Many Java developers who are not familiar with Groovy, view it as just a scripting language. Groovy is not just a scripting language. It is an Object Oriented Programming language, just like Java is. Some may argue that Groovy is a pure object oriented language and Java is not because of Java’s support of Primitive Types. Because unlike Java, Groovy does autoboxing of primitive types.

Its also important to understand, Groovy was never intended to be a replacement of Java. It’s written to supplement Java. As such, its very easy to mix and match code. Ultimately both Groovy and Java compile down to JVM byte code, and the compiled code is compatible.

Polyglot Programming in the Spring Framework

The Spring Framework is no stranger to Polyglot programming. The Grails community really spearheaded things with the Groovy language. In version 4 of the Spring Framework, we’re seeing a lot more support of polyglot programming around the Groovy language. But in the various Spring Framework projects we’re seeing more polyglot programming support around the Scala programming language. With Rod Johnson involved with Typesafe, I think it’s a safe bet we will see additional support of Scala in Spring in the future.

Groovy Spring Beans

It is possible to write Spring Beans in Groovy. Your application will compile and run just fine. Whenever programming for Dependency Injection, I recommend developing your code to an interface.

AddressService

When doing polyglot programming, I prefer to write the interface in Java. Now any class, written in Java or Groovy can implement the interface. You probably could write the interface in Groovy and use it in Java just fine, but there are some pitfalls of using Groovy from Java you need to be aware of. For example if you use ‘ def ‘ as a type, Java treats it as a Object  data type. Sometimes the strong typing of Java is not a bad thing. This also seems more appropriate to me when defining the interface to use.

AddressServiceImpl.groovy

You can see my Groovy class simply implements the AddressService  interface. I mark the class with the @Service("addressService")  annotation as I would a normal Java Spring Bean. 

Using a link below, you can checkout the full project. You will see the Groovy class compiles with the Java code and runs in the Spring context like any other Spring Bean.

Conclusion

In enterprise Java / Spring shops, you probably will not see much Polyglot programming. But, the Grails team uses Groovy for Spring Beans all the time. I’ve demonstrated its easy to use Groovy Spring beans outside of the Grails environment. This is not a technology issue to overcome. Culturally, I suspect it may be some time before you see polyglot programming in large scale enterprise applications. But doing polyglot programming like this is something fun to do in blog posts!

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share
,

This past week I had a real world use case for using Spring Integration Futures. I was looking into optimizing the checkout experience for a large ecommerce website. Consider what happens in a large scale website when an order is submitted. Typically, you will see a process something like:

  • Validate the place order form information
  • Verify the address against an address service
  • Verify the credit card with a payment processor
  • Verify available inventory

Each of these in a large scale enterprise are services. For example, it is common for an enterprise to subscribe to an address validation service. This helps ensure shipping accuracy. Or you’ll have a inventory service to help manage inventory levels. Normally not a problem. But when you have a black friday shopping special and thousands of users shopping on the site, managing inventory can become tricky.

Each of these services will take some time to execute. If called in sequence, the website response time slows down and impacts the user experience in the checkout flow. However, in my example here, there is no reason these service calls couldn’t be called concurrently. By calling the services concurrently, the response time now is the longest service call, not the sum of all the service calls. If each service call takes a half second, calling the services sequentially would take 2 seconds of elapsed time. Calling them concurrently only takes a half second.

A couple weeks back I wrote a blog post on testing Spring Integration Gateways.  In this use case, Spring Integration is the perfect tool. Spring Integration has a very cool feature to support asynchronous calls. When using Spring Integration Messaging Gateways, if you wrap the return time in a Java Future, Spring Integration will automatically handle the request in a different thread using a thread pool. As an application developer, this makes writing a multithreaded application very easy to do. The Spring Framework and Spring Integration handle the complexity of managing the worker threads and the thread pool.

In this post, I’m going to walk you through the configuration of the Spring Integration gateways and Spring service beans used to make these four service calls supporting my ecommerce place order example.

Spring Integration Code Examples

Command Objects

In this example, I’m going to use a command object. In a web application, this would typically have values bound to it from a form post. However, in today’s omni-channel retail environment, the website is not the only client I need to worry about. This request could be coming from a native iOS mobile application, a native Android mobile application, an in-store kiosk, or maybe a stand alone customer service application.

By using a command object, I’m decoupling my processing from the front end client. I don’t care where the request originated. Maybe it was a form post. Maybe a web service, could be a JMS request. It doesn’t really matter where the request originated.

Place Order Command

Domain Objects

For this example, I’ve created a couple domain objects. These are just simple POJOs I’m using to illustrate the example. In a real application these objects would be much more robust. 

Order

OrderLine

Product

Spring Integration Gateways

For this example, I’ve defined four different Spring Integration Messaging Gateways. Technically, I could have used just one Spring Integration Messaging Gateway, but that would have been a violation of the Single Responsibility Principle. This approach does lead to more class files. But when I need to maintain this code, I know where to look. The programming logic is clear and organized.

OrderGateway

The Order Gateway interface defines two methods. The first placeOrder  is the start of our processing chain.  This is where we will submit the command object. The second method is used in our the processing of the place order command object.

Note: notice the usage of the Java Future  for the return time of the validateOrder method. This is what instructs Spring Integration to perform the method call asynchronously using a thread pool.

AddressGateway

InventoryGateway

PaymentGateway

Spring Services

Since this is a Spring project, we’ll create our services as Spring Beans, and naturally will we be using Dependency Injection and program to an interface.

OrderService

OrderServiceImpl

The implementation of our Order Service is one of the more complex classes in this tutorial. You can see we are having Spring autowire our four Spring Integration Messaging Gateways into the class. In the placeOrderMethod , you can see I call a method on each of the four Spring Integration Gateways. Each method returns a Java Future. After all four are submitted, I go back to get the value of the Future. In this case, I’m using the Spring Errors object. If all four validation steps come back without errors, in a real system I’d persist the order to the database and do any post processing. But this is just a little sample to show off the use of Spring Integration Futures. So in this case, I’m just returning the command object either way.

Spring Integration Configuration

I had to expand on the Spring Integration configuration from our previous example. You’ll see I’m using the Spring Integration Gateway tag to define the four Spring Integration Gateways we’re using. Then I defined the Spring Integration channels and the appropriate Spring Integration service activators. Nothing new here over the previous example. Just a little more routing to take care of.

Notice how I did not define a thread pool? By default, Spring Integration is providing a thread pool for our use. You can of course define your own or update the settings of the default thread pool if needed.

si-config.xml

Running the Spring Integration Code

I’ve setup a Spock test to run the Spring Integration code in this example. 

OrderGatewayTests

When you run this Spock test you will see the following output:

Each the services I’ve wired into this example do simple print line statements out to the console. Each starts their respective output with the Id number of the thread they are running in. You can see from the output how each service is running concurrently in different threads.

Conclusion

As a programmer, Spring Integration is a very powerful tool to have in your toolbelt. You can see from this example how I’ve created a multithreaded application with a minimal amount of coding. I simply wrapped the return type I wanted on the Spring Integration Messaging Gateways with a Java Future. Spring Integration and Spring managed the thread pool for me. I didn’t need to worry about managing threads. The Spring Framework allowed me to focus on delivering the business solution, and took care of the complex boiler plate code.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share

Spring Integration Gateways are one of my favorite features of Spring Integration. As a developer, you write an interface for the Spring Integration Gateway, and at runtime Spring Integration will provide you an implementation of the class via the Spring Context for your application to use.

What is nice about this approach, the complexities of the messaging layer is completely hidden from your application code. There is no ‘leakage’ of the messaging layer into your application layer. From the standpoint of the developer, you are simply making a method call on a class which implements the interface you wrote for your Spring Integration Gateway.

Spring Integration Gateway Example

Overview

For our example today, lets say you’re working on a large ecommerce website. You need to call a service to retrieve product data. Spring Integration is a natural choice to handle this type of request. For integration with the service on the website, you’ve decided to use a Spring Integration Gateway. This way the message based request to the backend service is completely abstracted from your existing code.

Model

For our example, we want to return a product. In a large ecommerce web site, your Product class would be much more complex. However, this simple POJO is fine for demonstrating the capabilities of Spring Integration.

Spring Integration Gateway

Here is the code for our Spring Integration Gateway. This is the interface you will use in your application. 

Product Service

The Product Service could be a number of things in a real enterprise application. Might be a web service, could be a JMS or AQMP queue, a Spring Data Repository, or even a traditional DAO. For this demonstration, keep in mind this would be some type of different service you’d call to retrieve product data. I’ve created a very simple stub of a service class that just returns a Product  object.

Spring Integration Configuration

Knowing I want to unit test my Spring Integration Gateway, I’ve decided to split up my configuration files. There’s actually a couple different ways I could have approached this in Spring, such as using Profiles. However, for what I wish to accomplish today composing the Spring configuration works just fine. 

si-product-gateway.xml

In this configuration I’m defining just the gateway and the channels. Nothing else.

si-config.xml

For my production configuration, I import the Spring Integration configuration and the provide the rest of my Spring configuration. This is the Spring Configuration file I will use for my production environment.

Sprint Boot Application

Spring Boot makes it very easy to bring up the Spring context and execute our Spring Integration example application.  In this class, you can see I’ve used the @SpringBootApplication  to bring up the Spring Context. I’m sourcing in the Spring Integration Configuration with the @ImportResource  annotation. When this this application runs, it will get the application context and ask for an instance of our Spring Integration Gateway. Notice in the above code, I never provided a concrete implementation of the Gateway interface. This is something that Spring Integration will do for you at run time. Once I have the ProductGateway  from the Spring context, I can ask it for a Product .

When you run this class, you will see this output:

Testing the Spring Boot Application

The Spring Boot Application, actually becomes a Spring Configuration. You can actually run this example as a JUnit Test.

Running this will produce the same output as above. While this is ‘testing’ our Spring Integration Gateway via JUnit, it is not really what we want. The configuration is still using our ‘production’ ProductService . 

Unit Testing The Spring Integration Gateway

Technically what I’m showing you is not a ‘Unit’ test. Many will argue once you bring up a Spring Context, your test is now an ‘Integration’ test. I’ll let you decide what to call it.  To test my Spring Integration Gateway, I want to wire in a completely different service. In a real enterprise application, I would not want to be using the real product service for testing. I want to use some type of mock implementation. 

Gateway Test Service

Here is the mock service I want to wire into my Spring Integration Gateway for testing. Very similar to the fake service I provided for our example above, in the fact that it just creates a Product instance and returns it. For purposes of illustration, you can see I’m setting the product description to: 

Spring Configuration

Above I mentioned using composition for our Spring configuration in testing. Once you become more comfortable with the Spring Framework, you will find this is a very common technique to use. You will recall, I defined just the Spring Integration Gateway interface and channels in a Spring Integration file. For my unit tests, I can provide a completely different Spring Configuration. This in effect completely changes the plumbing behind the Spring Integration Gateway. 

JUnit Test of the Spring Integration Gateway

Here is a JUnit Test of the Spring Integration Gateway. In our test, we’re running it with the Spring JUnit Test Runner and specifying our test configuration for Spring.

When you run the above test, it will pass the assertions. Also in the console you will see the following output:

Notice how the product description is ‘Product In Testing’, proving that our test service was used, and not our ‘production’ service.

Spock Test of the Spring Integration Gateway

For fun, lets run the same test using Spock. Spock has become my favorite testing framework to use. If you’re not using Spock, you should be!

When you run the Spock Specification, you will see the following output:

Again, you can see all the assertions passed, and the output is ‘Product in Testing’.

Conclusion

Spring Integration Gateways are a great feature of Spring Integration. In this blog post, I’ve shown you how you can compose your Spring configuration files to change the behavior of Spring Integration for testing. I hope you can see how easy it is to wire up different configurations in Spring and Spring Integration.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.
0
Share
,

Spring Integration is a very powerful module in the Spring Framework. It was originally inspired by pivotal book in computer science called Enterprise Integration Patterns written by Gregor Hohpe and Bobby Woolf. While the Gang of Four focused their work on software design patterns, Enterprise Integration Patterns is focused on how disparate systems communicate with each other. As the industry has moved to highly scalable systems adopting cloud computing paradigms, the principles set forth in Enterprise Integration Patterns are highly relevant to Java programming.

Similar to the GoF focus, Spring Core largely focused on development within a single application or JVM environment.  Spring Integration builds upon the core principles of Spring Core to extend the Spring programming model to a message driven programming model. Abstracted from the developer when making a method call is the implementation details. Does it really matter if the method you are calling is a simple method call, a web service, a JMS Message, or making a request to the database? No, it should not. And more importantly, the implementation details should not leak back into your code.

In this example, I’ll step through the use of a Spring Integration Message Gateway for a classic “Hello World” programming example. I’ll show you how to use a Spring Integration Messaging Gateway for a simple send message, a request / response example, and an async request response example.

Spring Integration Hello World Code Example

Hello World Service Bean

For our example, we’re going to use a very simple service bean to either say hello or get a hello message. In a real world example, this code could be a direct method call, behind a web service, or perhaps its a message driven bean off a AQMP queue.

Spring Integration Gateway

The next component we need to setup is an interface class, which we will use for the Spring Integration Gateways. When coding to use Spring Integration, messaging gateways are a very convenient programming option to use. They have a very minimal impact on your application code. As the developer, you only need to create the interface specification. Spring Integration will provide the actual implementation and inject it into your class at run time. There is one small bit of leakage into your application code with the @Gateway  annotation. I could have coded this example without the annotations, but I find them very convenient to use. This annotation directs Spring Integration which messaging channel to use for the method call of the interface.

Spring Integration Gateway Configuration

The messaging gateway needs to be defined in your Spring Integration configuration. Spring Integration will not create the gateway bean without this configuration line.

Spring Integration Channel

Spring Integration Channels are a core concept to Spring Integration. They are used to decouple message producers (our gateway) from message consumers (our hello world bean). This abstraction is important because the channel could be a direct method call, or a JMS queue. The important take away is the decoupling. Neither the message producer nor the message consumer is aware of details about the implementation of the messaging channel.

In XML configuration snippet below, I’ve defined two messaging channels. Spring Integration has a number of options for defining messaging channels. The default channel is a direct channel, which is perfect for our hello world example.

Spring Integration Service Activator

Spring Integration has a concept of Service Activators. This is basically a way to configure a message consumer on a channel. This is completely decoupled from the gateway. Its important to remember the service activator is associated with a channel, and not a gateway or a gateway method. When you’re new to Spring Integration, it can be easy to lose site of this important distinction.

In this XML configuration snippet, I’ve defined two service activators.

Spring Integration XML Configuration

The complete XML configuration used in our hello world example follows below. You’ll see that I’m using a component scan to create the Hello World Service bean in the Spring context.

Running the Spring Integration Hello World Example

I’ve setup two examples to run our Spring Integration Hello World example. One using Spring Boot, and the second using JUnit. 

Spring Boot Application

In this example, I’m using Spring Boot to bring up the Spring Context. Since I placed the Spring Integration configuration in a XML configuration file, I need to use the @ImportResource  annotation to tell Spring Boot to import the XML configuration file.  In the code, I ask the Spring Context for an instance of the gateway bean. Then I call our three methods. The first is a simple send message with no return value. Our messaging service bean will write the hello message to the console. In the second example, I’m getting a message back from the Hello World Service bean.  The final example is a little more interesting. In this case, I’ve setup an asynchronous call. By specifying a Future in the return type, Spring Integration will automatically make a asynchronous call. This is an ideal technique to use when you have a longer running call (such as a remote web service), and you can do other work while the call is being made.

When you execute the above code, you will receive the following output in the console.

JUnit Example

We can run the same code as a JUnit test as well. In this case, I’m allowing Spring to autowire the Spring Integration gateway into my test. Then I have three separate tests to execute our three different hello world examples.

This is more typical of how you would use a Spring Integration gateway in your application code. You can utilize dependency injection in Spring to inject an instance of the Spring Integration gateway instance into your class at run time.

When you run the JUnit tests in this class, you will get the following output in the console.

Conclusion

This has been a very simple Hello World example using Spring Integration. While this post only scratches the surface of the abilities of Spring Integration, I hope you can see how easy it is to utilize Spring Integration in your code. As you learn to develop large scale enterprise applications, you will find that Spring Integration is an important module in the Spring Framework.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I am a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share