The best way to get started using Spring-Integration in your project is with a dependency management system, like gradle.
dependencies {
compile 'org.springframework.integration:spring-integration-core:4.3.5.RELEASE'
}
Below is a very simple example using the gateway, service-activator message endpoints.
//these annotations will enable Spring integration and scan for components
@Configuration
@EnableIntegration
@IntegrationComponentScan
public class Application {
//a channel has two ends, this Messaging Gateway is acting as input from one side of inChannel
@MessagingGateway
interface Greeting {
@Gateway(requestChannel = "inChannel")
String greet(String name);
}
@Component
static class HelloMessageProvider {
//a service activator act as a handler when message is received from inChannel, in this example, it is acting as the handler on the output side of inChannel
@ServiceActivator(inputChannel = "inChannel")
public String sayHello(String name) {
return "Hi, " + name;
}
}
@Bean
MessageChannel inChannel() {
return new DirectChannel();
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
Greeting greeting = context.getBean(Greeting.class);
//greeting.greet() send a message to the channel, which trigger service activitor to process the incoming message
System.out.println(greeting.greet("Spring Integration!"));
}
}
It will display the string Hi, Spring Integration!
in the console.
Of course, Spring Integration also provides xml-style configuration. For the above example, you can write such following xml configuration file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:gateway default-request-channel="inChannel"
service-interface="spring.integration.stackoverflow.getstarted.Application$Greeting"/>
<int:channel id="inChannel"/>
<int:service-activator input-channel="inChannel" method="sayHello">
<bean class="spring.integration.stackoverflow.getstarted.Application$HelloMessageProvider"/>
</int:service-activator>
</beans>
To run the application using the xml config file, you should change the code new AnnotationConfigApplicationContext(Application.class)
in Application
class to new ClassPathXmlApplicationContext("classpath:getstarted.xml")
. And run this application again, you can see the same output.