安裝或設定
在專案中開始使用 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")
。再次執行此應用程式,你可以看到相同的輸出。