2015-01-20 67 views
0

我已經工作:你可以結合Jersey和Spring(@Provider和@Component)嗎?

  1. Spring版本4.1.4.RELEASE
  2. 澤西島版本2.14
  3. 我加入行家依賴性球衣-spring3和排除彈簧從它(彈簧芯,彈簧網,彈簧豆)。
  4. 掃描彈簧組件 - @ComponentScan
  5. 「控制器」 被登記在新澤西州的ResourceConfig ...
  6. ...與@Path@Component被註釋...
  7. ...讓@Autowired豆取(@Transactional)來自數據庫的POJO ...
  8. ...和澤西島在某些@Provider幫助下以JSON的形式返回它們。

什麼似乎是問題是一個註釋類@Provider停止工作,只要我添加註釋@Component

有沒有人成功地組合這些註釋?如果是,那麼我錯過了什麼?如果不是這樣,那麼很顯然我必須轉向其他圖書館。 :)

+0

你打算使用球衣做什麼?休息? – 2015-01-20 20:54:56

+1

@KubaSpatny Jersey也有一些好的一面。你爲什麼這麼討厭它?版本2.x真的很體面:) – 2015-01-20 21:23:50

+0

@ R4J哦不,我不討厭它。我剛剛發現使用RestController更容易設置Spring上下文。 – 2015-01-20 21:25:16

回答

1

雖然我覺得用RestController可能是更好的方式去,這個代碼(如下)的作品 - 所以我的答案可能是大家誰是被迫使用澤西+春季(無論出於何種原因有用.. )

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.ApplicationContext; 

import javax.persistence.EntityNotFoundException; 
import javax.ws.rs.core.Response; 
import javax.ws.rs.ext.ExceptionMapper; 
import javax.ws.rs.ext.Provider; 

@Provider 
public class EntityNotFoundExceptionMapper implements ExceptionMapper<EntityNotFoundException> { 

    private final ApplicationContext applicationContext; 

    @Autowired 
    public EntityNotFoundExceptionMapper(ApplicationContext applicationContext) { 
     this.applicationContext = applicationContext; 
    } 

    @Override 
    public Response toResponse(EntityNotFoundException exception) { 
     return Response.status(Response.Status.NOT_FOUND).build(); 
    } 
} 
+0

一個重要的注意事項:注射工程,但範圍不。所以問題**的答案可以混合提供者和組件** **將不可靠**。 :) – Nebril 2015-01-20 21:50:15

+0

是的,用Spring Boot去吧! ;) – 2015-01-20 22:03:25

1

你可以使用Spring的RestController,這是在春季4.0增加。它允許您使用Autowired等等。

@RestController 
@RequestMapping("/msg") 
public class MessageRestController { 

    @Autowired 
    private IShortMessageService shortMessageService;  

    @RequestMapping(value = "/message-json/{id}", method = RequestMethod.GET, produces = "application/json") 
    public ShortMessageDto getMessageJSONById(@PathVariable String id) { 
      Long id_value = null; 
      try { 
       id_value = Long.parseLong(id); 
       ShortMessageDto message = shortMessageService.getById(id_value); 
       if(message != null){ 
       return message; 
      } catch (NumberFormatException e){ 
       // log message      
      }     
       return null; 
     } 

} 
相關問題