2016-06-08 111 views
0

基本上,我希望能夠在JSON中發佈對象並使用Java打印此對象的詳細信息。使用駱駝與彈簧引導來建立一個REST應用程序

爲了惟願我想(我要)使用Spring-BOOT和駱駝

這是代表我的對象的類:

public class Response { 
    private long id; 
    private String content; 

    public Response(){ 

    } 

    public Response(long id, String content) { 
     this.id = id; 
     this.content = content; 
    } 

    public long getId() { 
     return id; 
    } 

    public void setId(long id) { 
     this.id = id; 
    } 

    public String getContent() { 
     return content; 
    } 

    public void setContent(String content){ 
     this.content = content; 
    } 

} 

然後,我有一個休息控制器:

@RestController 
public class BasicController { 

    private static final String template = "Hello, %s!"; 
    private final AtomicLong counter = new AtomicLong(); 

    //Handle a get request 
    @RequestMapping("/test") 
    public Response getResponse(@RequestParam(value="name", defaultValue="World") String name) { 
     System.out.println("Handle by spring"); 
     return new Response(counter.incrementAndGet(), 
          String.format(template, name)); 
    } 

    //Handle a post request 
    @RequestMapping(value = "/post", method = RequestMethod.POST) 
    public ResponseEntity<Response> update(@RequestBody Response rep) { 

     if (rep != null) { 
      rep.setContent("HANDLE BY SPRING"); 
     } 
     return new ResponseEntity<Response>(rep, HttpStatus.OK); 
    } 
} 

有了這段代碼,我可以處理一個帖子請求和打印細節,但我必須使用駱駝。所以我tryed如下:

1)我加了一個bean的conf

@SpringBootApplication 
public class App 
{ 

    private static final String CAMEL_URL_MAPPING = "/camel/*"; 
    private static final String CAMEL_SERVLET_NAME = "CamelServlet"; 

    public static void main(String[] args) { 
     SpringApplication.run(App.class, args); 
    } 

    @Bean 
    public ServletRegistrationBean servletRegistrationBean() { 
     ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), CAMEL_URL_MAPPING); 
     registration.setName(CAMEL_SERVLET_NAME); 
     return registration; 
    } 
} 

2)然後,我創建了2路。

<?xml version="1.0" encoding="UTF-8"?> 
<routes xmlns="http://camel.apache.org/schema/spring"> 
<!--  <route id="test"> --> 
<!--   <from uri="timer://trigger"/> --> 
<!--   <to uri="log:out"/> --> 
<!--  </route> --> 
    <route id="test2"> 
     <from uri="servlet:///test"/> 
     <to uri="log:Handle by camel"/> 
    </route> 
</routes> 

有了這個,我可以在駱駝上提出請求。但我不知道如何使春天和駱駝之間的聯繫。有沒有辦法用我的彈簧控制器處理請求,然後調用駱駝路線?在相同的URL上。

回答

3

您可以使用自動裝配的producerTemplate來呼叫駱駝路線。

<dependency> 
    <groupId>org.apache.camel</groupId> 
    <artifactId>camel-spring-boot</artifactId> 
    <version>${camel.version}</version> <!-- use the same version as your Camel core version --> 
</dependency> 

欲瞭解更多信息,你可以看到駱駝文檔here:如果添加的依賴將被創建。

在你的情況,你會打電話是這樣的:

producerTemplate.sendBody... 
相關問題