安装或设置
在项目中开始使用 Spring-Integration 的最佳方法是使用依赖管理系统,例如 gradle。
dependencies {
compile 'org.springframework.integration:spring-integration-core:4.3.5.RELEASE'
}
//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!"));
}
}
它将在控制台中显示字符串 Hi, Spring Integration!
。
当然,Spring Integration 还提供了 xml 风格的配置。对于上面的示例,你可以编写以下 xml 配置文件。
<?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>
要使用 xml 配置文件运行应用程序,你应该将 Application
类中的代码 new AnnotationConfigApplicationContext(Application.class)
更改为 new ClassPathXmlApplicationContext("classpath:getstarted.xml")
。再次运行此应用程序,你可以看到相同的输出。