Building a Restful Web Service Using Spring Boot, Spring Initializer, MongoDB and Swagger

Kawee Lokuge
3 min readJun 8, 2018

Setting Up

Go to https://start.spring.io/

Generate a MAVEN Project with Java and Spring Boot 2.0.2

Group — com.springpractice

Artifact — first-springapp

Selected Dependencies — Web, MongoDB

Click on Generate Project

Extract the Zip File and Open the Project in Eclipse/IDE.

Add the following dependencies in the POM.xml file under dependencies –

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>

Project Directory Structure

Create the following directory structure under :

first- springapp\src\main\java

  • controller
  • model
  • repository
  • service

Overview

We are creating a CRUD Application for Insert, Get, Update and Delete a User. User consist of 2 properties: user id, name.

Let’s Start Coding!

Defining the Model

Create User class under the model package. The structure of the mongoDB user instance is defined in this class.

package model;import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="users")
public class User {
@Id
private String id;
private String name;

public String getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


}

Defining the Repository

Create UserRepository Interface under the repository package. This interface extends from the MongoRepository. This interface is used to access the database.

package repository;import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import model.User;
@Repository
public interface UserRepository extends MongoRepository<User,String>{
}

Defining the Service

Create UserService interface under the service package. This interface defines all the methods that controller can access.

package service;import java.util.List;import model.User;public interface UserService {
User createUser(User user);
User updateUser(String id, User user);
User deleteUser(String id);
User getUser(String id);
List<User> listUsers();

}

Create UserServiceImpl class under the service package. This class implements all the methods defined in the UserService interface. UserServiceImpl separates all the method implementations and business logic from the controller.

package service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import model.User;
import repository.UserRepository;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@SuppressWarnings("finally")
private User findOne(String Id) {
User instance = null;
try {
List < User > userList = userRepository.findAll();
for (User user: userList) {
if (user.getId().equals(Id)) {
instance = user;
break;
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
return instance;
}
}
@Override
public User createUser(User user) {
return userRepository.save(user);
}
@Override
public List < User > listUsers() {
return userRepository.findAll();
}
@Override
public User updateUser(String id, User user) {
User updateInstance = this.findOne(id);
updateInstance.setName(user.getName());
return userRepository.save(updateInstance);
}@Override
public User deleteUser(String id) {
User instance = findOne(id);
userRepository.delete(instance);
return instance;
}@Override
public User getUser(String id) {
//return userRepository.findById(id).get();
return this.findOne(id);
}
}

Defining the Controller

Create UserServiceController class under the controller package. Controller handles all the routes.

package controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import model.User;
import service.UserService;
@RestController@RequestMapping("/users")
public class UserServiceController {
@Autowired
private UserService userService;
@RequestMapping(method = RequestMethod.POST)
public User createUser(@RequestBody User user) {
return userService.createUser(user);}@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public User updateUser(@PathVariable String id, @RequestBody User user) {
return userService.updateUser(id, user);
}
@RequestMapping(method = RequestMethod.GET)
public List < User > listUsers() {
return userService.listUsers();
}@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable String id) {
return userService.getUser(id);
}@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public User deleteUser(@PathVariable String id) {
return userService.deleteUser(id);
}
}

Running the Project

Open cmd in windows or terminal if you are in Mac/Linux.

Go inside the project directory and issue command mvn clean install

References -

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

https://docs.mongodb.com/

--

--