2017-09-26 92 views
-1

我正在使用Spring Boot(1.5.3)創建Spring REST Web服務。我添加了spring-boot-starter-web作爲唯一的依賴項(按照彈簧指南)。接下來,我爲我的服務類創建了UserManagementService接口。在API類中添加REST Web服務註釋

@RequestMapping("/usermanagement/v1") 
public interface UserManagementService { 

    @RequestMapping(value = "/user/{id}/", method=RequestMethod.GET) 
    public UserTo getUserById(@PathVariable("id") long id); 

    @RequestMapping(value = "https://stackoverflow.com/users/", method=RequestMethod.GET) 
    public List<UserTo> getAllUsers(); 
} 

及其實施UserManagementServiceImpl

@RestController 
public class UserManagementServiceImpl implements UserManagementService { 

    private Map<Integer, UserTo> users; 

    public UserManagementServiceImpl() { 
     users = new HashMap<>(); 
     users.put(1, new UserTo(1, "Smantha Barnes")); 
     users.put(2, new UserTo(2, "Adam Bukowski")); 
     users.put(3, new UserTo(3, "Meera Nair")); 
    } 

    public UserTo getUserById(long id) { 
     return users.get(id); 
    } 

    public List<UserTo> getAllUsers() { 
     List<UserTo> usersList = new ArrayList<UserTo>(users.values()); 
     return usersList; 
    } 

} 

我想創建一個REST Web服務使用Spring啓動與最低配置,並認爲這是可行的。但是在訪問我的Web服務時,我得到了No Response。我錯過了什麼?

此外,我看到很多項目的註釋添加到接口,而不是實現類。我認爲這比註釋類更好。它應該在這裏工作,對吧?

+1

您必須檢查,但我不確定註釋是否被接口正確處理,因爲它不是實例化的確切類。在更基於觀點的思想中,您應該以相同的方式爲用戶調用您的服務:我的意思是@RequestMapping(value =「/ users/{id} /」,method = RequestMethod.GET)'' RequestMapping(value =「/ users /」,method = RequestMethod.GET)',因爲您希望用戶列表中的所有用戶或一個用戶。但評論的第二部分取決於你。 – DamCx

+1

@DamCx我嘗試了不同的場景,並且「@PathVariable」似乎不能在界面中的方法聲明中工作。它僅在實現類中工作。代碼中的其餘註釋在界面中工作正常。 –

回答

0

由於mentioned in the comments,並非所有的註釋都支持接口。該@PathVariable註釋例如將無法正常工作,所以你必須把上實現本身:

public UserTo getUserById(@PathVariable("id") long id) { 
    return users.get(id); 
} 

此外這一點,你有一個Map<Integer, UserTo>,但你檢索使用@PathVariable的用戶鍵入long。這也不行,所以要麼改變usersLong鍵或id參數int

public UserTo getUserById(@PathVariable("id") int id) { 
    return users.get(id); 
} 

這樣做的原因是,1Llong)是不一樣的1int)。因此,檢索地圖項不會返回long值的任何結果。