2016-06-08 36 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... 
相关问题