简体   繁体   中英

Adding REST Web Service annotation in API class

I am using Spring Boot (1.5.3) to create a Spring REST Web Service. I have added spring-boot-starter-web as the only dependency (as per spring guide). Next I have created UserManagementService interface for my service class.

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

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

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

And its implementation 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;
    }

}

I wanted to created a REST Web Service using Spring Boot with minimum configuration and thought this would work. But on accessing my the Web Service I am getting No Response. What I am missing?

Also, I have seen many projects where annotations are added to the interface rather than the implementation class. Which I think is better than annotating classes. It should work here, right?

As mentioned in the comments , not all annotations are supported on interfaces. The @PathVariable annotation for example won't work, so you'll have to put that on the implementation itself:

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

Additionally to that, you have a Map<Integer, UserTo> , but you're retrieving the users using a @PathVariable of type long . This won't work either, so either change the key of users to Long or the id parameter to int :

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

The reason for this is that 1L ( long ) is not the same as 1 ( int ). So retrieving a map entry wouldn't return any result for a long value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM